How to get selected checkbox values in jQuery

No comments
Getting all selected checkbox values in the query is very easy. With below example, you can get all selected checkbox's value in comma separated. This will help you in sending these values in SQL parameters or if you are trying to fill values in any input type, for example text or text-area, etc. In the example below, I have used google Jquery library version 2.2.2.

HTML Code:
Add any number of check boxes in your page as below. And call showSelectedValues() function on onclick event.
<div>
   <input name="chkboxName" type="checkbox" value="Click Me 1" checked>Click Me 1
   <input name="chkboxName" type="checkbox" value="Click Me 2">Click Me 2
   <input name="chkboxName" type="checkbox" value="Click Me 3">Click Me 3
   <input name="chkboxName" type="checkbox" value="Click Me 4">Click Me 4
   <input name="chkboxName" type="checkbox" value="Click Me 5">Click Me 5
<input type="button" name="clickme" value="Click Me" onclick="showSelectedValues();" />
  </div> 
JavaScript Code:
Now create a JavaScript function and name it showSelectedValues()  and pass the textbox name as below:
function showSelectedValues()
{
  alert($("input[name=chkboxName]:checked").map(
     function () {return this.value;}).get().join(","));
}

Output will be like below:


Complete source code:
Below is the complete source code. You can customise it as per your requirement and don't forget to comment if you are facing any issue and Of course, you can give your feedback/suggestions.
<html>
  <head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
 </head>
 <body>
  <div>
   <input name="chkboxName" type="checkbox" value="Click Me 1" checked>Click Me 1
   <input name="chkboxName" type="checkbox" value="Click Me 2">Click Me 2
   <input name="chkboxName" type="checkbox" value="Click Me 3">Click Me 3
   <input name="chkboxName" type="checkbox" value="Click Me 4">Click Me 4
   <input name="chkboxName" type="checkbox" value="Click Me 5">Click Me 5
<input type="button" name="clickme" value="Click Me" onclick="showSelectedValues();" />
  </div>  
<script type="text/javascript">
function showSelectedValues()
{
  alert($("input[name=chkboxName]:checked").map(
     function () {return this.value;}).get().join(","));
}
</script>
 </body>
 </html>

No comments :

Post a Comment