vendredi 28 février 2020

If a checkbox is checked, REQUIRE a text field to be filled in. Text field is FAILING: always required regardless of checkbox status

I have a group of 3 check boxes. If the one labelled as "mouthpiece" is checked, then the text field labelled mpTxt must NOT be left blank for the form to validate. Currently, the form is requiring the mpTxt field to be filled regardless of what is checked.

HTML:

 <div class="col-6">
    <b><u>Interface </u></b><br>
    <input id="F429_interfaceTrachCkBx" class="F429_backupV" name="F429_interfaceTrachCkBx" 
type="checkbox">
    Trach 
    <input id="F429_interfaceMaskCkBx" class="F429_backupV" name="F429_interfaceMaskCkBx" 
type="checkbox">
    Mask 
    <input id="mouthpiece" class="F429_backupV" name="F429_interfaceMouthpieceCkBx" type="checkbox">
    Mouthpiece <br>
</div>

 Mouthpiece Ventilation (MPV) Settings 
 <input id="mpTxt" class="F429_mpvSetting" name="F429_mpvSetting" type="text">

JavaScript:

//REQUIRE MPV TEXT IF CKBX CHECKED

var checkBox = document.querySelector('input[id="mouthpiece"]');
var textInput = document.querySelector('input[id="mpTxt"]');

function toggleRequired() {

if (textInput.hasAttribute('required') !== true) {
    textInput.setAttribute('required','required');
}

else {
    textInput.removeAttribute('required');  
}
}

checkBox.addEventListener('change',toggleRequired,false);



Aucun commentaire:

Enregistrer un commentaire