简体   繁体   中英

Selected attribute in option tag

I have a dropdown that's populated through a loop. The selected attribute should be added when <%if o.getNextPage()%> is equal to i .

 <select id="dropDown" onchange="display(this.value)"> var start = 1; var end = noOfPages; var options = ""; for (var i = start; i <= end; i++) { options += "<option>" + i + "</option>"; } document.getElementById("dropDown").innerHTML = options; function display(e) { document.getElementById("hidden").value = e; document.invoiceForm.submit(); }

You can add value attribute to the option tag.

As suggested by @3Dos in comments you can use 'document.createElement' without needing to insert raw HTML like this:

var start = 1;
var end = noOfPages;
var options = "";
for (var i = start; i <= end; i++) {
    var opt = document.createElement('option');
    opt.value = i;
    opt.innerHTML = i;
    document.getElementById('dropDown').appendChild(opt);
}

This is the proper way of generating your dropdown list and preserve performance as you interact with the DOM only once thanks to the documentFragment

 // These were not provided by OP but added to actually get this snippet running var noOfPages = 5; var start = 1; var end = noOfPages; var options = document.createDocumentFragment(); for (var i = start; i <= end; i++) { var option = document.createElement('option'); option.value = i; option.textContent = i; options.appendChild(option); } document.getElementById("dropDown").appendChild(options);
 <select id="dropDown" onchange="display(this.value)"></select>

I omitted the display function which is irrelevant as it refers to unprovided code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM