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

前端 未结 7 1199
我在风中等你
我在风中等你 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 09:48

    Your code works for me. When does addSalespersonOption get called? There may be a problem with that call.

    Also some of your html is a bit off (maybe copy/paste problem?), but that didn't seem to cause any problems. Your select should look like this:

    
    

    instead of this:

    
    

    Edit: When does your options list get dynamically populated? Are you sure you are passing 'on' for the defSales value in your call to addSalespersonOption? Try changing that code to this:

    if (selected == "on") { 
        alert('setting default selected option to ' + text);
        html = ''; 
    } 
    

    and see if the alert happens and what is says if it does happen.

    Edit: Working example of my testing (the error:undefined is from jsbin, not my code).

提交回复
热议问题