how to set text of option:selected in jquery

596 views Asked by At
<select id="myselect">
    <option value="1">Mr</option>
    <option value="2">Mrs</option>
    <option value="3">Ms</option>
    <option value="4">Dr</option>
    <option value="5">Prof</option>
</select>

<select id="youSelect">
    <option value="1">Mr</option>
    <option value="2">Mrs</option>
    <option value="3">Ms</option>
    <option value="4">Dr</option>
    <option value="5">Prof</option>
</select>

Now on click of a button I want to set mySelect option:selected value in youSelect So for this I had done this

$('#youSelect option:selected').text($('#myselect option:selected').text())

but its not working.Please guide how to solve this.

4

There are 4 answers

1
rrk On

Use this.

$(selector_to_your_button).on('click',function(){
    $('#youSelect).val($("#myselect").val());
});
0
Rutunj sheladiya On
$("#youSelect").val("thevalue");

just make sure the value in the options tags matches the value in the val method.

0
Sang Suantak On

Simply do:

$('#youSelect').val($('#myselect').val());

You are matching the values, not the text.

Edit: Based on your edited question, you're probably looking at the same situation as this question

var _mySelectText = $("#myselect option:selected").text();
$("#youSelect option").filter(function () {
    return this.text === _mySelectText;
}).attr("selected", "selected");
5
n00b On
  var myValue = $("#myselect option:selected").text();
  var secondoption = $("#youSelect")[0];


  for (var i = 0, sL = secondoption.length; i < sL; i++) {
    if (secondoption.options[i].text == myValue) {
      secondoption.selectedIndex = i;
      break;
    }
  }

http://plnkr.co/edit/GVt8rZswjzZTC13vw98N?p=preview