How to set the 'selected option' of a select dropdown list with jquery
Asked Answered
S

8

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>
Swanner answered 25/7, 2013 at 11:18 Comment(5)
Have you checked the value of result[0] matches what you're expecting?Streamy
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?Swanner
Okay, after some trials this issue is created by jquery ui and jquery mobile. without them this works 100%. see fiddle jsfiddle.net/szpgF. any way around this? thanks.Swanner
Check this: codingfusion.com/Post/…Harp
Check this: codingfusion.com/Post/…Harp
C
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

Cutlor answered 25/7, 2013 at 11:36 Comment(4)
Thanks. Tried this with no luck. :-(Swanner
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 jsfiddle.net/szpgFSwanner
if you see source code it is selecting correctly but may be changing z-index or font color might display it.Rumor
Edited again for jQuery Mobile, check the link I added. I tried it in the fiddle and it seemed to work well.Cutlor
R
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
Rumor answered 25/7, 2013 at 11:21 Comment(4)
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?Swanner
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,Swanner
Hi Zaheer, it appears Jquery Mobile or Jquery UI is affecting this. see my fiddle jsfiddle.net/szpgF. if I take away UI and Mobile, it works correctly. any ideas around this?Swanner
.val() doesn't set the selected="selected" attribute, nor does it deselect other options if they are selected.Selfannihilation
C
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());
Coomer answered 6/1, 2015 at 19:43 Comment(3)
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...)Intonation
@RJBrill :) nice, glad to have helped with my stupidityCoomer
hi, how to append the <option Value>.. as well, in my case for e.g. the options are being copied from a dynamically populated template like the date+Day WhenSelectedVenireman
H
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>
Hyperplasia answered 17/7, 2015 at 3:25 Comment(0)
T
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>
Tibold answered 16/2, 2017 at 6:25 Comment(1)
You took code posted several months before yours, that already doesn't answer the question, and made it so it doesn't work.Gerena
I
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;
    }
}
Indigo answered 18/7, 2022 at 13:21 Comment(0)
S
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();
Selfannihilation answered 5/11, 2021 at 17:42 Comment(0)
T
-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.

Thirtyone answered 11/12, 2017 at 9:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.