I cannot figure out why my script is not triggering. I am trying to create form validation for this select element, requiring that is the Other
option is chosen, then the following input field be set as required
. As it is, the other_lab
input field is not becoming required
when Other
is chosen in the select element. Here is the code:
<form id="form_1" method="post">
<label for="lab">Lab</label>
<select id="lab" required name="lab">
<option disabled selected value="">Choose lab</option>
<option value="Lab_1">ABC</option>
<option value="Lab_2">DEF</option>
<option value="Other">Other</option>
</select>
<label for="other_lab">If other, please specify: </label>
<input name="other_lab" id="other_lab" size="15">
</form>
<script type="text/javascript">
var form = document.getElementById('form_1');
form.onsubmit = function (e){
if(document.getElementById('lab').value == "Other") {
document.getElementById('other_lab').setAttribute("required","");
}else{
document.getElementById('other_lab').removeAttribute("required","");
}
}
</script>