Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting option by text content with jQuery

Tags:

jquery

I want to set a dropdown box to whatever has been passed through a querystring using jquery.

How do I add the selected attribute to an option such that the "TEXT" value is equal to a certain param from the query string?

 $(document).ready(function() {         var cat = $.jqURL.get('category');         if (cat != null) {             cat = $.URLDecode(cat);             var $dd = $('#cbCategory');             var $options = $('option', $dd);             $options.each(function() {                 if ($(this).text() == cat)                     $(this).select(); // This is where my problem is             });         };     }); 
like image 924
OneSmartGuy Avatar asked Jun 17 '09 21:06

OneSmartGuy


People also ask

How do you select option by text?

Select from option value is pretty easy and it is as below: $('select option[value="test"]'). val(); So now selecting by text, If you are using jQuery and if you have an older version than 1.9 the following will work choosing by text.

How do I select a Dropdownlist using jQuery?

if your options have a value, you can do this: $('select'). val("the-value-of-the-option-you-want-to-select"); 'select' would be the id of your select or a class selector. or if there is just one select, you can use the tag as it is in the example.

How can I get multiple selected values of select box in jQuery?

With jQuery, you can use the . val() method to get an array of the selected values on a multi-select dropdown list.


1 Answers

Replace this:

var cat = $.jqURL.get('category'); var $dd = $('#cbCategory'); var $options = $('option', $dd); $options.each(function() { if ($(this).text() == cat)     $(this).select(); // This is where my problem is }); 

With this:

$('#cbCategory').val(cat); 

Calling val() on a select list will automatically select the option with that value, if any.

like image 52
Paolo Bergantino Avatar answered Sep 22 '22 05:09

Paolo Bergantino