This is the part of HTML I have got to show month between Feb to Oct
<div>
<select name="interval" id="sInterval">
<option value="2">2</option>
<option value="3">3</option>
<option selected value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<span>*2</span>
</div>
So I got a JS list to contain the month info
var months=["2","3","4","5","6","7","8","9","10"]
and a function that add two month to the end to help shown the select box from Feb to Dec
function addmonth(thelist) {
thelist.push("11");
thelist.push("12");
}
addmonth(months)
I want the HTML become like this
<div>
<select name="interval" id="sInterval">
<option value="2">2</option>
<option value="3">3</option>
<option selected value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
<span>*2</span>
</div>
How could I achieve this? is it possible? or should I do it on pure HTML? because the JS list is received from Jquery so it is necessary in this case.
CodePudding user response:
you can try something like this
const targetParent = document.getElementById("sInterval")
["11","12"].forEach(month =>
const optionElement = document.createElement("option")
optionElement.innerText = month;
optionElement.setAttribute("value",month)
targetParent.append(optionElement))
CodePudding user response:
You need to add the options to the select element after updating months array.
If you are using jQuery, Then you can simply use append() method.
var months=["2","3","4","5","6","7","8","9","10"]
function addmonth( month ) {
months.push( month );
$("#sInterval").append(`<option value="${month}"> ${month} </option>`);
}
addmonth("11");
addmonth("12");
CodePudding user response:
you should change menu all dynamic
in html ) <select id="menu'> </select>
in js - put this code on the <body onl oad='menu_maker()' >
let month = [1,2,3,4,5,6,7,8,9,10,11,12];
function menu_maker(){
for (var i in month){ // rounding in list
var option = document.createElement("option");
option.value = month[i];
option.innerHTML = month[i];
option.style = 'classname'
var select = document.getElementById('menu');
select.appendChild(option);
}
}
