I want to verify the checkboxes checked property. If any of them is not checked, display this sentence in span: "you should select one of them" and when I choose one of them, the 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 one of them');
bool = false;
}
if(checkedCount >= 1)
{
$("#textspan").html('');
bool = true;
}
return bool;
}
You did not add any function to the change (or click) event of your checkboxes:
your function 'vali()' is attached to form submit It means your function will work only if you click on send button
So If you have your error, and you want to not have it when you click one of them(checkboxes), you have to add one function to that event:
function vali() {
var bool = true;
var checkedCount = $('input[class="gender"]:checked').length;
if (checkedCount == 0) {
$("#textspan").html('select one 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 your click event is triggered whenever you click one of your '.gender', its better to have your function as:
$(".gender").click(function(){
$("#textspan").html('');
});
try below
<form method="get"action="#" onsubmit="return vali();">
<span id="textspan" style="color:red"></span>
<input type="radio" name="rad" class='gender' id="male">male
<input type="radio" name="rad" class='gender' id="female">female
<input type="submit" class="validate" value="send" />
</form>
<script>
$(document).ready(function(){
$(".gender").click(function(){
$("#textspan").html('');
});
});
function vali() {
var bool = true;
var checkedCount = $('input[class="gender"]:checked').length;
if (checkedCount == 0) {
$("#textspan").html('select one of them');
bool = false;
}
if(checkedCount >= 1)
{
$("#textspan").html('');
bool = true;
}
return bool;
}
</script>
fiddler like :- here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With