javascript - HTML checkbox validation breaks when there are multiple checkboxes in the form -
in form below, how ignore disabled checkbox. expected behavior in form if user not check model check box , click on submit button, form should submitted. if model checkbox checked, user must enter data. behavior works long there no other checkbox on page. if there checkbox, , submit button clicked without checking model checkbox, alert thrown. how can ignore other checkboxes in form achieve desired behavior? thanks!
$(document).ready(function () { $('#checkmodelbtn').click(function() { var ischeckboxchecked = $("input[type=checkbox]:checked").length; var istextentered = $("input.childmodel").val().length; if ( istextentered || !ischeckboxchecked ) { //alert("validation passed!"); } else { alert("please enter model number"); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <table> <tr> <td> <p><h2>model:</h2></p> <input type="checkbox"> model # <input type="text" size="12" class="childmodel"><br> </td> <td> checkbox breaks functionality<p> <input type="checkbox" checked disabled> text here</td> </tr> </table> <hr> <input type="submit" name="submit" value="submit" id="checkmodelbtn"/>
to ignore checkbox don't want validate need way ignore in validation, , can using input field. change selector checkbox $("input[type=checkbox]:checked")
$(".childmodel").prev("input[type=checkbox]:checked")
example:
$(document).ready(function() { $('#checkmodelbtn').click(function() { var ischeckboxchecked = $(".childmodel").prev("input[type=checkbox]:checked").length; var istextentered = $("input.childmodel").val().length; if (istextentered || !ischeckboxchecked) { //alert("validation passed!"); } else { alert("please enter model number"); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <table> <tr> <td> <p> <h2>model:</h2> </p> <input type="checkbox"> model # <input type="text" size="12" class="childmodel"> <br> </td> <td> checkbox breaks functionality <p> <input type="checkbox" checked disabled> text here</td> </tr> </table> <hr> <input type="submit" name="submit" value="submit" id="checkmodelbtn" />
Comments
Post a Comment