Javascript and JQuery, how to verify if option element exists in select?

前端 未结 3 943
梦如初夏
梦如初夏 2021-01-12 07:28

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

相关标签:
3条回答
  • 2021-01-12 07:57

    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
    
    0 讨论(0)
  • 2021-01-12 07:59

    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();
    
    0 讨论(0)
  • 2021-01-12 08:23

    try to check selectObject.find('option[value="'+valueToSelect +'"]').length > 0

    0 讨论(0)
提交回复
热议问题