36

I have the following jquery function:

$.post('GetSalesRepfromCustomer', {
    data: selectedObj.value
}, function (result) {
    alert(result[0]);
    $('select[name^="salesrep"]').val(result[0]);
});

result[0] is a value that I want to set as the selected item in my select box. result[0] equals Bruce jones.

the select box is populated by a database query but one of the rendered html is:

<select id="salesrep" data-theme="a" data-mini="true" name="salesrep">
<option value=""> </option>
<option value="john smith">john smith</option>
<option value="Bruce Jones">Bruce Jones</option>
<option value="Adam Calitz">Adam Calitz</option>
<option>108</option>
</select>

$('select[name^="salesrep"]').val(result[0]); doesn't populate the select box selected option. I have also tried $("#salesrep").val(result[0]); without any luck.

Any help appreciated.

so what I want is the selected / highlighted option in the salesrep dropdown list to be Bruce Jones.

HTML to be:

<select id="salesrep" data-theme="a" data-mini="true" name="salesrep">
<option value=""> </option>
<option value="john smith">john smith</option>
<option value="Bruce Jones" selected >Bruce Jones</option>
<option value="Adam Calitz">Adam Calitz</option>
<option>108</option>
</select>

Thanks again,

Entire Script

<script type="text/javascript"> 
    $(document).ready(function () {

           $("#customer").autocomplete( 
     { 
     source: "get_customers", 
     messages: 
     { 
     noResults: '', 
     results: function() {} 
     }, 
     select: function( event, ui ) 
     { 
      var selectedObj = ui.item;        

     $.post('GetSalesRepfromCustomer', {data:selectedObj.value},function(result) { 
      alert(result[0]);
       var selnametest="Bruce Koller";
    $("#salesrep").val(selnametest);
     }); 

     } 
     });
         });


</script>

Rendered HTML is:

<select id="salesrep" data-theme="a" data-mini="true" name="salesrep">
<option value=""> </option>
<option value="RyanLubuschagne">Ryan Lubuschagne</option>
<option value="Bruce Jones">Bruce Jones</option>
<option value="Adam Calitz">Adam Calitz</option>
</select>
Smudger
  • 10,451
  • 29
  • 104
  • 179
  • 2
    Have you checked the value of `result[0]` matches what you're expecting? – Rory McCrossan Jul 25 '13 at 11:22
  • 1
    Hi, yes, I did check this thanks. The rendered HTML select element is real. even if I try `$("#salesrep").val('bruce Jones')` it does not work? anything to do with PHP populating the select options? – Smudger Jul 25 '13 at 11:29
  • Okay, after some trials this issue is created by jquery ui and jquery mobile. without them this works 100%. see fiddle http://jsfiddle.net/szpgF/. any way around this? thanks. – Smudger Jul 25 '13 at 12:32

8 Answers8

59

Try this :

$('select[name^="salesrep"] option[value="Bruce Jones"]').attr("selected","selected");

Just replace option[value="Bruce Jones"] by option[value=result[0]]

And before selecting a new option, you might want to "unselect" the previous :

$('select[name^="salesrep"] option:selected').attr("selected",null);

You may want to read this too : jQuery get specific option tag text

Edit: Using jQuery Mobile, this link may provide a good solution : jquery mobile - set select/option values

Community
  • 1
  • 1
Jb Drucker
  • 972
  • 8
  • 14
  • Thanks. Tried this with no luck. :-( – Smudger Jul 25 '13 at 11:46
  • I Jean, okay this is affected by jquery mobile and jquery UI. if I remove these it works 100%. how can I get around this as I need ui and mobile? see my fiddle on http://jsfiddle.net/szpgF/ – Smudger Jul 25 '13 at 12:31
  • if you see source code it is selecting correctly but may be changing z-index or font color might display it. – Zaheer Ahmed Jul 25 '13 at 12:49
  • Edited again for jQuery Mobile, check the link I added. I tried it in the fiddle and it seemed to work well. – Jb Drucker Jul 25 '13 at 15:18
37

Set the value it will set it as selected option for dropdown:

$("#salesrep").val("Bruce Jones");

Here is working Demo

If it still not working:

  1. Please check JavaScript errors on console.
  2. Make sure you included jquery files
  3. your network is not blocking jquery file if using externally.
  4. Check your view source some time exact copy of element stop jquery to work correctly
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
  • Thanks, I have added my complete script. Please see if there is an underlying cause although I don't get any errors from firebug. the syntax you gave doesn't work on my side and not sure why? – Smudger Jul 25 '13 at 11:33
  • 1
    Zaheer, tried your fiddle on my site without any php populated select field and it still doesn't work. My Jquery UI and Jquery Mobile is being loaded after Jquery 1.9.1. any ideas? If I try and populate a notmal text box it work just fine. just struggling with the select list? Thanks, – Smudger Jul 25 '13 at 11:48
  • 1
    Hi Zaheer, it appears Jquery Mobile or Jquery UI is affecting this. see my fiddle http://jsfiddle.net/szpgF. if I take away UI and Mobile, it works correctly. any ideas around this? – Smudger Jul 25 '13 at 12:30
  • 1
    `.val()` doesn't set the `selected="selected"` attribute, nor does it deselect other options if they are selected. – vapcguy Nov 05 '21 at 17:48
5

One thing I don't think anyone has mentioned, and a stupid mistake I've made in the past (especially when dynamically populating selects). jQuery's .val() won't work for a select input if there isn't an option with a value that matches the value supplied.

Here's a fiddle explaining -> http://jsfiddle.net/go164zmt/

<select id="example">
    <option value="0">Test0</option>
    <option value="1">Test1</option>
</select>

$("#example").val("0");
alert($("#example").val());
$("#example").val("1");
alert($("#example").val());

//doesn't exist
$("#example").val("2");
//and thus returns null
alert($("#example").val());
Jake Zieve
  • 455
  • 1
  • 6
  • 14
  • I also made the same stupid mistake and this answer helped at a critical point. My mistake was trying to set the val() to the option text itself and not the value attribute of the required option (they were both very similar, but with different case...) – R Brill Jan 06 '15 at 22:07
  • @RJBrill :) nice, glad to have helped with my stupidity – Jake Zieve Jan 06 '15 at 23:50
  • hi, how to append the ` – Transformer Mar 18 '17 at 06:53
5

You have to replace YourID and value="3" for your current ones.

$(document).ready(function() {
  $('#YourID option[value="3"]').attr("selected", "selected");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<select id="YourID">
  <option value="1">A</option>
  <option value="2">B</option>
  <option value="3">C</option>
  <option value="4">D</option>
</select>

and value="3" for your current ones.

$('#YourID option[value="3"]').attr("selected", "selected");

<select id="YourID" >
<option value="1">A </option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
Oscar Fuquen
  • 459
  • 5
  • 2
3

$(document).ready(function() {
  $('#YourID option[value="3"]').attr("selected", "selected");
  $('#YourID option:selected').attr("selected",null);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<select id="YourID">
  <option value="1">A</option>
  <option value="2">B</option>
  <option value="3">C</option>
  <option value="4">D</option>
</select>
Madhuka Dilhan
  • 1,396
  • 1
  • 14
  • 21
  • You took code posted several months before yours, that already doesn't answer the question, and made it so it doesn't work. – Arielle Lewis Dec 18 '17 at 21:05
1

Use $('select[id="salesrep"]').val() to retrieve the selected value.

Use $('select[id="salesrep"]').val("john smith") to select a value from dropdown.

OR, you can use the following JS code:

for (var option of document.getElementById("salesrep").options) {
    //alert(option.value);
    if (option.value === "john smith") {
        option.selected = true;
        return;
    }
}
srihitha
  • 371
  • 2
  • 14
0

.val() doesn't like to set by text, but by using the index, instead, so you should do a find to get that, then set by it. But even that is only part of the story. You should first deselect all other options, and set the attribute of the option you want as selected using the index that you find.

I would not make the value and text the same, just so you have a positive assertion of what you are actually grabbing - the value vs. text - so you know what you are dealing with and don't run into these kinds of problems.

Btw, I hate the $('#myId') syntax because it is useless in SharePoint because it auto-generates GUIDs and puts them after the IDs, forcing you to have to grab it with $('[id*=myID]'), with the * indicating that it contains that value, so that is how I will set this up, except I'll leave out the * because it's unnecessary in this case. But this syntax is also very useful if you want to use $ instead of * to say it starts with that value, and you can use title or name instead of id, so it is incredibly versatile, and I wish more people used it.

You should also correct your capitalization issues, because JavaScript is case-sensitive.

$(document).ready(function() {
    var yourText = "Bruce Jones";

    // Remove all 'selected' attributes from all options
    $('select[id="salesrep"] option').removeAttr('selected');

    // Get the index for the value you want to set
    var idx = $('select[id="salesrep"] option').filter(function() {
        return $(this).html() == yourText;
    }).val();

    // Set the dropdown value by index and set it as selected by text
    var salesrepBox = $('select[id="salesrep"]');
    salesrepBox.val(idx);
    salesrepBox.find('option[value="' + yourValue + '"]').attr('selected','selected'); // note that .val() doesn't do this
    salesrepBox.click(); // may be useful and necessary for certain engines to cache the value appropriately

    console.log(salesrepBox.html()); // should show you that the selected option is Bruce Jones
    console.log(salesrepBox.val());  // should give you the index 2

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<select id="salesrep">
  <option value="1">John Smith</option>
  <option value="2">Bruce Jones</option>
  <option value="3">Adam Calitz</option>
</select>

For jQuery Mobile, you may need to do this after the lines that affect the dropdown's selected attribute, whether removing it or adding it:

salesrepBox.selectmenu("refresh", true);

Or do a .change(); on the end of the commands above, ex:

$('select[id="salesrep"] option').removeAttr('selected').change();
salesrepBox.find('option[value="' + yourValue + '"]').attr('selected','selected').change();
vapcguy
  • 7,097
  • 1
  • 56
  • 52
-2

The match between .val('Bruce jones') and value="Bruce Jones" is case-sensitive. It looks like you're capitalizing Jones in one but not the other. Either track down where the difference comes from, use id's instead of the name, or call .toLowerCase() on both.

Black Mantha
  • 1,147
  • 8
  • 11