Reputation: 55
I am trying to enable a select box when an option is selected in another select box. In this case, when a user selects R or C in the first select box, the second box should be enabled. I have attempted to replicate the solution here: Selectbox disabled or enabled by an option of an other selectbox, however the form I am using is set up for submit and rest buttons, as well as many other input and select fields. I am also very new to Javascript and HTML so if there is something silly that I have done, I won't be entirely surprised.
My Javascript function is the following, which is placed after the HTML body code:
<script type="text/javascript">
document.getElementById("part").onchange = function ()
{
if (document.getElementById("part").value == "R" || document.getElementById("part").value == "C")
{
document.getElementByID('part_number').disabled = false;
}
else
{
document.getElementByID('part_number').disabled = true;
}
}
</script>
And the select boxes are:
<select class="form-control" name="part[]" id="part" style="display: inline-block; width: 50%;" data-index="1">
<option value disabled selected> -- Select a part -- </option>
<option value='R'>R</option>
<option value='C'>C</option>
</select>
<select multiple class="form-control" name="part_number[]" id="part_number" style="display: inline-block; width: 50%;" disabled>
<option value disabled selected> -- Select a part -- </option>
<?php for ($i = 1; $i < 100; $i++){?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php } ?>
</select>
The second box holds the options 1-99 and is disabled by default. The two text boxes can be replicated many times through a dynamic Javascript function which is why I am using arrays. There are no errors in the console of my browser either. I am using the latest version of Google Chrome. Any help would be greatly appreciated. Thank you.
Upvotes: 0
Views: 70
Reputation: 33857
You are not getting the selected value of the dropdown list correctly:
<script type="text/javascript">
document.getElementById("part").onchange = function ()
{
var partList = document.getElementById("part");
var selectedPart = partList.options[partList.selectedIndex].value;
if (selectedPart === "R" || selectedPart === "C")
{
document.getElementById('part_number').disabled = false;
}
else
{
document.getElementById('part_number').disabled = true;
}
}
</script>
Upvotes: 1
Reputation: 3327
The only issue with your code is that you're using getElementByID
(with capital D) instead of getElementById
inside the if else
instruction
It should read:
if (selectedPart === "R" || selectedPart === "C")
{
document.getElementById('part_number').disabled = false;
} else {
document.getElementById('part_number').disabled = true;
}
Upvotes: 2