Harry Palmer Harry Palmer - 5 months ago 14
HTML Question

Disable different Inputs based on Option selected from a <select> element

I'm creating a contact us form, which should concede of multiple Text Inputs, A Text area & a Submit button. Above this form should be a drop down selection with three options in this example I've used 'Select an Option','Option 1' & 'Option2'.

I'm trying to get it so that all of the elements on the form are disabled unless 'Option 1' is selected. So if either of the other 2 are selected, the form should not be accessible by the user.

Currently I've managed to figure out how to disable one input but the other one doesn't seem to work the same way. What is the reason behind this? Also how can I get it to disable the other elements?



function checkOption(obj) {
var input = document.getElementById("input");
input.disabled = obj.value == "A";
}

<p>Contact Us Form </P>

<select id="menu" onChange="checkOption(this)">
<option value="A">Select An Option</option>
<option value="B">Option 1</option>
<option value="A">Option 2</option>
</select>

<br>
<p> First Name </p>
<input type="text" id="input" disabled>

<p> Second Name </p>
<input type="text" id="input" disabled>

<p>Enquiry</p>
<textarea rows="4" cols"50" id="textarea">
Lorem ipsum dolor sit amet, an modo mucius eum,
sanctus concludaturque qui no. Stet esse intellegat no eam,
nonumes eligendi disputationi ad usu.
</textarea>

<br>
<input type="submit" value="Submit">




Answer

Try this : first of all don't use same id for multiple input (elements), use class or name attribute instead of id. Get all elements by name and then disable-

function checkOption(obj) {
    var input = document.getElementsByName("input");
    for(var i=0; i < input.length; i++) {
     input[i].disabled = !(obj.value == "B")
    }
}
<p>Contact Us Form </P>

<select id="menu" onChange="checkOption(this)">
    <option value="A">Select An Option</option>
    <option value="B">Option 1</option>
    <option value="A">Option 2</option>
</select>

<br>
<p> First Name </p>
<input type="text" name="input" disabled>

<p> Second Name </p>
<input type="text" name="input" disabled>

<p>Enquiry</p>
<textarea rows="4" cols"50" id="textarea" name="input" disabled>
Lorem ipsum dolor sit amet, an modo mucius eum,
sanctus concludaturque qui no. Stet esse intellegat no eam,
nonumes eligendi disputationi ad usu.
</textarea>

<br>
<input type="submit" value="Submit" name="input" disabled>