Javascript und JQuery, wie um zu überprüfen, ob die option element besteht in der Auswahl?

Verwendung von JQuery, ich versuche eine option, wie ausgewählt, in der ein 'select' - Elements auf der Basis der query-string.

Diese Frage ist ähnlich diese, aber ich muss noch wissen, wie um zu prüfen, ob das element vorhanden ist, vor der Durchführung der Auswahl, sonst wird die Seite aktualisiert sich ständig (siehe die Bedingung beenden unten).

Abrufen der query-string ist getan mit der Funktion getParameterByName, und es funktioniert gut.

Die aktuelle Implementierung unter:

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: die Lösung, Die geklappt hat war:

    //Checks if the option exists, and returns otherwise
    if (!selectObject.find('option[value=' + valueToSelect + ']').length)
        return;
  • Einstellung des Werts mit .val() wird, wählen Sie dieses Element, so warum benutzt du auch .attr('selected','selected')?
  • Dazu werde ich das Beispiel, wenn das funktioniert, vielen Dank
InformationsquelleAutor haschdl | 2012-03-14
Schreibe einen Kommentar