How do I programmatically set the value of a select box element using JavaScript?

后端 未结 17 1879
轮回少年
轮回少年 2020-11-22 06:33

I have the following HTML

17条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 06:57

    Most of the code mentioned here didn't worked for me!

    At last, this worked

    window.addEventListener is important, otherwise, your JS code will run before values are fetched in the Options

        window.addEventListener("load", function () {
                // Selecting Element with ID - leaveCode  //
                var formObj = document.getElementById('leaveCode');
    
                // Setting option as selected
                let len;
                for (let i = 0, len = formObj.length; i < len; i++){
                    if (formObj[i].value == '') 
                     formObj.options[i].selected = true;
                }
        });
    

    Hope, this helps!

提交回复
热议问题