Chann Chann - 3 months ago 12
Javascript Question

how to change selected item using jquery?

I have a html drop down as follwos

<select id="subCategory" class="style_1">
<option name="All" value="16,17,19,18,8,94" >All</option>
<option name="CBC" value="94" >CBC</option>
</select>


And i want to change the selected item using jquery as follows.

var subCategorySelected = "CBC";
$('#subCategory').find('option:contains(' + subCategorySelected + ')').attr({selected: "selected"});


But its not working. Can anyone help me find the mistake?

Answer

Your code is working!

var subCategorySelected = "CBC";    
$('#subCategory').find('option:contains(' + subCategorySelected + ')').attr({selected: "selected"});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="subCategory" class="style_1">
     <option name="All" value="16,17,19,18,8,94" >All</option>
     <option name="CBC" value="94" >CBC</option>
</select>

Just make sure the code is executed after page is completely loaded. This can be done by using any of the following

  1. Wrap the code in ready handler
  2. Move the script to the end of <body>

:contains will check if the passed string is contained anywhere in the element. So, if there are multiple elements which contains the string, this will select wrong options.

Example:

<select>
    <option something="something">ABC DEF</option>
    <option something="something">ABC</option>
    <option something="something">ABC XYZ</option>
</select>

Here, to select ABC - the second option, if we use :contains('ABC'), this will select the other option.

You may use Attribute Equals Selector [name=”value”]

$('#subCategory option[name="' + subCategorySelected + '"]').prop('selected', true);

The selector option[name="' + subCategorySelected + '"] will select the <option> element having name attribute value as the given value. Then selected property can be set using prop().

var subCategorySelected = "CBC";
$('#subCategory option[name="' + subCategorySelected + '"]').prop('selected', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="subCategory" class="style_1">
     <option name="All" value="16,17,19,18,8,94" >All</option>
     <option name="CBC" value="94" >CBC</option>
</select>


If you have the mapping of option text and value, using value the option can be selected as

$('#subCategory').val('94');