I am trying to change 3 text inputs to selects and append options underneath, but the input stays the same.
Here is my js code
let inputSelect=['protons2', 'atomic2', 'neutrons'];
for(let i = 0; i < inputSelect; i ){
document.getElementById(inputSelect[i]).setAttribute("type","select")
const opt = document.createElement("option");
opt.textContent = "orbit";
document.getElementById(inputSelect[i]).appendChild(opt)
}
here is my html code
<label id="pro2" for = "protons2"></label>
<input type = "text" id = "protons2" class='input' autocomplete="off" placeholder="Answer">
<label id="at2" for = "atomic2"></label>
<input type = "text" id = "atomic2" class='input' autocomplete="off" placeholder="Answer">
<label id="new" for = "neutrons"></label>
<input type = "text" id = "neutrons" class='input' autocomplete="off" placeholder="Answer">
The input type does change according to the css selector input[type=text], as none of the styles of that selector is applied once the text input changes to a select input. It still stays a text input though.
CodePudding user response:
1 - You have to use the length value in the array to use it in the for.
2 - You can't convert an input text into a select. You have to replace the element.
let inputSelect = [ 'protons2' , 'atomic2' , 'neutrons' ] ;
for(let i = 0; i < inputSelect.length; i ){
select_aux = document . createElement ( "select" ) ;
select_aux . id = inputSelect [ i ] ;
document . getElementById ( inputSelect [ i ] ) . replaceWith ( select_aux ) ;
const opt = document . createElement ( "option" ) ;
opt . textContent = "orbit" ;
document . getElementById ( inputSelect [ i ] ) . appendChild ( opt ) ;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" id="protons2">
<input type="text" id="atomic2">
<input type="text" id="neutrons">
</body>
</html>
CodePudding user response:
There is no type attribute that is select, instead you need to make a select element.
Note: You forgot to add .length to inputSelect in your loop.
<select>
<option>Option 1</option>
</select>
Creating a select with JS
document.insertAdjacentHTML('beforeend', '<select>
<option>Option 1</option>
</select>')
let inputSelect=['protons2', 'atomic2', 'neutrons'];
for(let i = 0; i < inputSelect.length; i ){
const opt = document.createElement("option");
opt.textContent = "orbit";
document.getElementById(inputSelect[i]).appendChild(opt)
}
<select id="protons2">
</select>
<select id="atomic2">
</select>
<select id="neutrons">
</select>
