How to Get Selected Check boxes Values in jQuery


0


The checkbox is very helpful to get multiple values. The selected checkboxes value is send on form submission to the server-side. But if you wish to get the selected checkboxes values without form submit, jQuery is the good option. The selected checkboxes value can get simply using jQuery. In the tutorial code sample, I will show you how to get selected checkboxes value in jQuery.

The given sample code will help you out to get all values checked checkboxes by class name / ID in jQuery.

In the given HTML, the val_chk class is set to every checkbox. Likewise, a button is located under the checkboxes, that trigger the jQuery code to catch the values of every selected checkboxes.

HTML Code

<!-- checkboxes -->
<div><input type="checkbox" value="1" class="chk"> Value 1</div>
<div><input type="checkbox" value="2" class="chk"> Value 2</div>
<div><input type="checkbox" value="3" class="chk"> Value 3</div>
<div><input type="checkbox" value="4" class="chk"> Value 4</div>
<div><input type="checkbox" value="5" class="chk"> Value 5</div>

<!-- button to get values -->
<input type="button" id="getValue" value="Get Selected Checkboxes Value">

Include the jQuery library.

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

The given jQuery code snippet gets the every selected checkboxes value. If selected, checked checkboxes values are show, in other ways, an alert appears.

Also Read:

$(document).ready(function(){
    $('#getValue').on('click', function(){
        // Declare a checkbox array
        var chkArray = [];
        
        // Look for all checkboxes that have a specific class and was checked
        $(".chk:checked").each(function() {
            chkArray.push($(this).val());
        });
        
        // Join the array separated by the comma
        var selected;
        selected = chkArray.join(',') ;
        
        // Check if there are selected checkboxes
        if(selected.length > 0){
            alert("Selected checkboxes value: " + selected);	
        }else{
            alert("Please select at least one checkbox.");	
        }
    });
});


Like it? Share with your friends!

0
Developer

0 Comments