javascriptjquery

Setting the value of a select element when generating HTML at runtime


I have some JavaScript that looks like this:

TheHTML = '<select>';
TheHTML = TheHTML + '<option value="1">first</option>'
TheHTML = TheHTML + '<option value="2">second</option>'
TheHTML = TheHTML + '</select>'

The HTML string is then add to the DOM with $(selector).html(TheHTML);

If I then want the second option to be selected, I need to add $(selector).find(select).val(2);

Is there a way to generate the HTML so that the select element has the second value selected when it's added to the DOM?


Solution

  • use the selected attribute

    TheHTML += '<option value="2" selected>second</option>'
    

    Demo: Fiddle