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;