1

I am trying to check whether the checkbox is checked or not using jquery when the checkbox inside the php foreach loop.

i am trying to pass the checkbox value using php foreach loop values are passed correctly but cehckbox validations are not working.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Checkbox Reference</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit(function(){
    valid = true;
    if($('input[type=checkbox]:checked').length == 0)
    {
        alert ( "ERROR! Please select at least one checkbox" );
        valid = false;
    }
    return valid;
});
});
</script>
</head>

<body>
<form  name="myform" id="myform" action="" method="post" onSubmit="return validate();">
<?php
$values = array(1,2,3,4,5);
foreach($values as $id)
{
echo "<input type='checkbox' name='checks[]' value='".$id."'><br>"; 
}

?>
<input type="submit" name="submit" value="submit">
</form>

<?php
?>
</body>
</html>
3
  • Is .length really what you want to check? Commented Sep 3, 2015 at 11:03
  • Just i want to validate this checkbox is checked or not when i submiting the form Commented Sep 3, 2015 at 11:14
  • Do you want to check if all of them were checked or at least one? Commented Sep 3, 2015 at 11:22

3 Answers 3

1

Could you try as following code:

$(document).ready(function(){

    $("#myform").submit(function(e){
        if($('[name="checks[]"]:checked').length === 0) {
            alert ( "ERROR! Please select at least one checkbox" );
            return false;
        }
        return true;
    });

});
Sign up to request clarification or add additional context in comments.

1 Comment

Just put the return valid inside the submit handler, so if the form is invalid it will not be sent.
0

Use jQuery instead of $ symbol. with php the $ symbol may cause conflict . I have solved your issue. you can check here

http://phpfiddle.org/main/code/mtzq-yd1i

Comments

0

i changed the code to this and it works:

$("#myform").submit(function(e){
        valid = true;
        var inputs = $('input[type=checkbox]:checked');
        if(inputs.length == 0)
        {
            console.log ( "ERROR! Please select at least one checkbox" );
            valid = false;
        }
        return valid;
    });

Try putting this code at the end of your html, even if you are using document.ready

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.