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 know how to check if the element exists before performing the selection, otherwise the page will refresh itself continously (see the exit condition below).
Fetching the query string is done using the function getParameterByName, and it's working fine.
The current implementation below:
function setSelectedItem(selectName, itemToSelect) {
///<summary>Selects an HTML option element inside a HTML select element based on the value from the query string.</summary>
///<param name="selectName" type="string">The partial name of the HTML select in which 'itemToSelect' must be selected</param>
///<param name="itemToSelect" type="string">The name of the query string parameter which value is the of the 'option' element to select.</param>
//If an items has already been selected, return
if ($('select[name*=' + selectName + ']')[0].selectedIndex != 0) return;
//Fetches the value from the query string; if empty, returns
var valueToSelect = getParameterByName(itemToSelect);
if (valueToSelect == "") return;
//Fecthes the HTML select object
var selectObject = $('select[name*=' + selectName + ']');
//HERE how to check if 'valueToSelect' does not exist and return?
selectObject.val(valueToSelect).attr('selected', 'selected').change();
}
Update: The solution which worked was:
//Checks if the option exists, and returns otherwise
if (!selectObject.find('option[value=' + valueToSelect + ']').length)
return;
How can I check whether a option already exist in select by jQuery? Check this: var IsExists = false; $('#ddlCity option').
var exists = $("#yourSelect option") . filter(function (i, o) { return o. value === yourValue; }) .
Use the tagName property to check if an element is a select dropdown, e.g. if (select. tagName === 'SELECT') {} . The tagName property returns the tag name of the element on which it was accessed. Note that the property returns tag names of DOM elements in uppercase.
try to check selectObject.find('option[value="'+valueToSelect +'"]').length > 0
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();
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