Home » Php » javascript – Fetch text from selected option and put it in textbox

javascript – Fetch text from selected option and put it in textbox

Posted by: admin February 25, 2020 Leave a comment

Questions:

Im using php to populate the Countries from database, and depends on what country is selected the Cities will show up in the second select box.

Now i Want the selected City show up in a textarea.
If user changes city again and then the textarea value need change to.

this is what i have.

    <div class="form-group">
      <label for="country_id" class="col-sm-3 control-label"><?php echo get_phrase('country'); ?></label>

      <div class="col-sm-7">
        <select name="country_id" id = "country_id" class="select2" data-allow-clear="true" data-placeholder="<?php echo get_phrase('select_country'); ?>" onchange="getCityList(this.value)">
          <option value="0"><?php echo get_phrase('none'); ?></option>
          <?php foreach ($countries as $country): ?>
            <option value="<?php echo $country['id']; ?>"><?php echo $country['name']; ?></option>
          <?php endforeach; ?>
        </select>
      </div>
    </div>

    <div class="form-group">
      <label class="col-sm-3 control-label" for="city_id"> <?php echo get_phrase('city'); ?></label>
      <div class="col-sm-7">
        <select class="form-control select2" name="city_id" id="city_id">
          <option value=""><?php echo get_phrase('select_city'); ?></option>
        </select>
<textarea id="myPick"></textarea>
      </div>
    </div>

I have tried add this javascript but nothing happens.

<script>
$('select[name="city_id"]').change(function(){
    var text = $(this).find("option:selected").text();
    if(text != ""){
       text = "Buy "+text;
    }

    $('#myPick').val(text);
});

</script>
How to&Answers: