Wednesday, July 15, 2015

Getting checkbox value using JQuery

                               This is how my HTML looks 


Here is the HTML and JS

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="jquery-2.1.4.js"></script>
     <script type="text/javascript">
         $(document).ready(function () {
             $('#btnSubmit').click(function () {
           
                 var result = $('input[type="checkbox"]:checked') // this return collection of items checked
                 if (result.length > 0) {
                     var resultString = result.length + " checkboxe(s) checked <br/><br/>"

                     result.each(function () {
                         resultString+= $(this).val() + "<br/>";
                     });

                     $('#divResult').html(resultString);

                 }
                 else {
                     $('#divResult').html(" No checkbox  is checked");
                 }

             });
         });
         

</script>
   
</head>
<body>
   Skills :
    <input type="checkbox" name="skills" value="JavaScript" /> JavaScript
    <input type="checkbox" name="skills" value="JQuery" /> JQuery
    <input type="checkbox" name="skills" value="C#" /> C#
    <input type="checkbox" name="skills" value="VB" /> VB
        <br />
    <br />
<input id="btnSubmit" type="submit" value="submit" />
    <br />
    <br />
    <div id="divResult">

    </div>
</body>
   

</html>


Results : 

It gets values of checkboxes that are selected on Submit button click event



If no checboxes are selected and Submit button is clicked appropriate message is displayed.




No comments:

Post a Comment