Using JQuery, I\'m trying to set an option as selected in a \'select\' element based on the query string.
This question is similar to this, however I still need to k
You could use .length>0
to check if the element does exist. But if you are running this code over and over again it get's kind of annoying so I have written a little plugin which ensures that kind of functionality:
/* doesExist PLUGIN (c) MS */
/* (c) Michael Stadler(MS), */
(function($){
$.fn.doesExist = function()
{
return jQuery(this).length > 0;
};
})(jQuery);
Usage:
$('#myDiv').doesExist() // returns a boolean
Check the length of the selector:
var selectObject = $('select[name*=' + selectName + ']');
if (selectObject.length == 0)
return;
selectObject.val(valueToSelect).attr('selected', 'selected').change();
Or use the implicit boolean conversion in javascript:
var selectObject = $('select[name*=' + selectName + ']');
if (!selectObject.length)
return;
selectObject.val(valueToSelect).attr('selected', 'selected').change();
try to check selectObject.find('option[value="'+valueToSelect +'"]').length > 0