How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?

前端 未结 7 1202
我在风中等你
我在风中等你 2021-02-04 09:17

For some reason, I can\'t get this to work.

My options list is populated dynamically using these scripts:

function addOption(selectId, value, text, sele         


        
7条回答
  •  日久生厌
    2021-02-04 10:02

    The defaultSelected attribute is not settable, it's just for informational purposes:

    Quote:

    The defaultSelected property returns the default value of the selected attribute.
    This property returns true if an option is selected by default, otherwise it returns false.

    I think you want:

    $('option[value=valueToSelect]', newOption).attr('selected', 'selected');
    

    I.e. set the selected attribute of the option you want to select.


    Without trying to fix your code, here's roughly how I would do it:

    function buildSelect(options, default) {
        // assume options = { value1 : 'Name 1', value2 : 'Name 2', ... }
        //        default = 'value1'
    
        var $select = $('');
        var $option;
    
        for (var val in options) {
            $option = $('');
            if (val == default) {
                $option.attr('selected', 'selected');
            }
            $select.append($option);
        }
    
        return $select;
    }
    

    You seem to have a lot of baggage and dependencies already and I can't tell you how to best integrate the selected option into your code without seeing more of it, but hopefully this helps.

提交回复
热议问题