jquery - Verify if checkbox checked property is not empty using JavaScript -
i want verify checkboxes checked property. if of them not checked, display sentence in span: "you should select 1 of them" , when choose 1 of them, message must disappear.
<form method="get"action="#" onsubmit="return vali();"> <span id="textspan" style="color:red"></span> <input type="checkbox" class='gender' id="male">male <input type="checkbox" class='gender' id="female">female <input type="submit" class="validate" value="send" /> </form>
function vali() { var bool = true; var checkedcount = $('input[class="gender"]:checked').length; if (checkedcount == 0) { $("#textspan").html('select 1 of them'); bool = false; } if(checkedcount >= 1) { $("#textspan").html(''); bool = true; } return bool; }
you did not add function change (or click) event of checkboxes:
your function 'vali()' attached form submit means function work if click on send button
so if have error, , want not have when click 1 of them(checkboxes), have add 1 function event:
function vali() { var bool = true; var checkedcount = $('input[class="gender"]:checked').length; if (checkedcount == 0) { $("#textspan").html('select 1 of them'); bool = false; } if(checkedcount >= 1) { $("#textspan").html(''); bool = true; } return bool; } $(".gender").click(function(){ var checkedcount = $('input[class="gender"]:checked').length; if(checkedcount >= 1){ $("#textspan").html(''); } });
as click event triggered whenever click 1 of '.gender', better have function as:
$(".gender").click(function(){ $("#textspan").html(''); });
Comments
Post a Comment