I'm trying to display the item according to the item selected in the box, but I can't display each item separately in the code below. how do I display the selected item in a paragraph for example??
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<form name="property_form">
<span>
<select class="select-car" name="the_menu">
</select>
</span>
</form>
<p id="demo"></p>
<script>
var cars = new Array();
var text = new Array();
cars[0] = "Saab";
tex[0] = "Saab 9-3 Viggen was the jet on wheels of the Swedish brand";
cars[1] = "Fiat";
cars[2] = "BMW";
document.getElementById("demo").innerHTML = cars;
function FillMenuWithArray(myMenu, myArray) {
// Fills the options of myMenu with the elements of myArray.
var i;
myMenu.length = myArray.length;
for (i = 0; i < myArray.length; i ) {
myMenu.options[i].text = myArray[i];
}
}
// This fragment initializes the property dropdown menu using the data defined above in the
'Data Definitions' section
window.onload = function(e) {
FillMenuWithArray(document.property_form.the_menu, cars)
}
</script>
</body>
</html>
CodePudding user response:
Your code had a few issues going on, so I found it best to write my own related version that you can reference from. You can run the code snippet here to see if that is what you are looking for.
var cars = {
Saab: "This is a Saab.",
Fiat: "I love Fiat.",
BMW: "Some people call BMW's a beamer."
}
var select = document.querySelector(".select-car");
var p = document.querySelector("p#demo");
Object.keys(cars).forEach(car => {
const option = document.createElement("option");
option.value = car;
option.append(car);
select.append(option);
})
select.onchange = function () {
p.innerText = cars[select.options[select.selectedIndex].value] || "";
};
<h2>JavaScript Arrays</h2>
<form name="property_form">
<span>
<select class="select-car" name="the_menu">
<option value="">Choose Car</option>
</select>
</span>
</form>
<p id="demo"></p>
CodePudding user response:
const p = document.querySelector("#demo");
var cars = new Array();
cars.push("Saab", "Fiat", "BMW");
var text = new Array();
text[0] = "Saab 9-3 Viggen was the jet on wheels of the Swedish brand";
text[1] = "Fiat9 Viggen brand";
function FillMenuWithArray(myMenu, myArray) {
// Fills the options of myMenu with the elements of myArray.
myMenu.innerHTML = myArray.map(c => `<option value='${c}'>${c}</option>`).join('');
}
window.onload = function(e) {
FillMenuWithArray(document.property_form.the_menu, cars);
// when changed on select change in paragraph
document.property_form.the_menu.addEventListener('change', function(e){
const ptext = text[e.target.selectedIndex-1] ?? '';
p.innerHTML = `<span>${ptext}</span>`;
});
}
<form name="property_form">
<select class="select-car" name="the_menu">
<option value="">Select car</option>
</select>
<p id="demo"></p>
</form>