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 }); }; });
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.
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.
With jQuery, you can use the . val() method to get an array of the selected values on a multi-select dropdown list.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With