Here's an example of how to modify the option value of a select box based on the ID number entered:
HTML code:
<select id="selectBox">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<input type="number" id="idNumber">
<button onclick="updateOption()">Update Option</button>
JavaScript code:
function updateOption() {
var selectBox = document.getElementById("selectBox");
var idNumber = document.getElementById("idNumber").value;
// Loop through all the options in the select box
for (var i = 0; i < selectBox.options.length; i++) {
var option = selectBox.options[i];
// Check if the ID number matches the option value
if (option.value === idNumber) {
option.selected = true; // Set the option as selected
return; // Exit the function
}
}
// If no option matches the ID number, show an error message
alert("Option not found");
}
This code first gets the select box and ID number input elements using their id
attributes. When the "Update Option" button is clicked, the updateOption()
function is called.
Inside the function, we loop through all the options in the select box using a for
loop. For each option, we check if its value
attribute matches the ID number input value. If it does, we set that option as selected
using its selected
property and then exit the function.
If none of the options match the ID number input value, an error message is displayed using JavaScript's alert()
method.
Asked: 2023-06-11 15:44:11 +0000
Seen: 7 times
Last updated: Jun 11 '23