<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>1</title>
<script src="main.js"></script>
</head>
<body onl oad="OnLoad()">
<form name="form">
<select name="weapons" onChange="SelectWeapon()"></select>
</form>
</body>
</html>
var weaponsArray = [
'Broadsword',
'Crossbow',
'Magic staff'
];
function onl oad() {
for (var i = 0; i < weaponsArray.length; i ) {
var wepType = "<option value = '" i "'>" weaponsArray[i] "</option>";
document.forms["form"]["weapons"] = wepType;
}
}
I'm trying to get the elements of the array to add to a select tag using document.forms by adding option tags to the array element and then adding it to the select tag.
I wanted this to end up populating a dropdown on a html page but the dropdown stays empty. I'm new to JavaScript so I am struggling to see where I have gone wrong.
CodePudding user response:
It's possible to use document.createElement to create an option, and then Element.append to add it to the select element:
var weaponsArray = [
'Broadsword',
'Crossbow',
'Magic staff'
];
function onl oad() {
for (let i = 0; i <weaponsArray.length; i ) {
// create a new option
const option = document.createElement('option');
option.value = i;
option.textContent = weaponsArray[i];
// add the option to the select element
document.forms.form.weapons.append(option);
}
}
<body onl oad="OnLoad()">
<form name="form">
<select name="weapons"></select>
</form>
</body>