Thursday, August 8, 2019

How to get all selected checkbox values in an array using PHP and jQuery?

In this blogs, I show you how to get all selected checkbox values in an array through PHP and jquery. Here you will easily get all selected checkbox values in php and jquery.

Please see below steps :

Step 1 : Define below jquery script

<script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

Step 2 : Add HTML and PHP code

<p id="title">Multiple Subject  Checkboxes</p>
<p>Before click on submit button please check few subject checkbox.</p>
<input type="checkbox" name="subject" value="English" /> English
<input type="checkbox" name="subject" value="Maths" /> Maths
<input type="checkbox" name="subject" value="Science" />Science
<br>
<button name="submit">Submit</button>
<p id="multicheck"></p> 

Step 3 : Add javascript

<script type="text/javascript">     
$('button').on('click', function() {
    var array = [];
    $("input:checked").each(function() {
array.push($(this).val());
    });
    $('#multicheck').text(array);
});
</script>

Step 4 :  Add CSS

<style>         
#multicheck {
     color: Red;
     font-weight: bold;
     font-size: 20px;
}       
button {
      margin-top: 20px;
      margin-left: 60px;
}
#title {
     color: blue;
     font-size: 26px;
     font-weight: bold;
}
</style>

Now, Here is Full PHP, HTML and Jquery code


<html>
<head>
    <title>
        Get all selected checkbox values in an array | PHP | Jquery
    </title>
    <style>         
        #multicheck {
                color: Red;
font-weight: bold;
                font-size: 20px;
        }       
        button {
                margin-top: 20px;
margin-left: 60px;
        }
#title {
color: blue;
font-size: 26px;
font-weight: bold;
}
    </style>
</head>
<script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> 
<body>
    <p id="title">Multiple Subject  Checkboxes</p>
    <p>Before click on submit button please check few subject checkbox.</p>
    <input type="checkbox" name="subject" value="English" /> English
    <input type="checkbox" name="subject" value="Maths" /> Maths
    <input type="checkbox" name="subject" value="Science" />Science
    <br>
    <button name="submit">Submit</button>
    <p id="multicheck"></p>
    <script type="text/javascript">     
        $('button').on('click', function() {
            var array = [];
            $("input:checked").each(function() {
                array.push($(this).val());
            });
            $('#multicheck').text(array);
        });
    </script>
</body> 
</html>

Output : 
  • Before select the checkboxes
  • After select the checkboxes show the values

Thats it !!!!

I hope it can help you...


No comments:

Post a Comment

Popular Posts