Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • Select only one element of checkbox at a time using jquery

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.72k
    Comment on it

    Many times we need to select only one element at a time in checkbox because mostly in checkbox is used for multiple data selection. This blog illustrate how we can select only one element of checkbox at a time using jquery.
    See the below Code:

    HTML page:

    <script src=""></script>
    <input type="checkbox" name="color" value="Pink"> I like pink color<br>
    <input type="checkbox" name="color" value="Red"> I like red color<br>
    <input type="checkbox" name="color" value="Green"> I like green color<br>
    <input id="btn" type="submit" value="Submit">
    <!--Scripting section-->
    <!-- Below code will allow the user to select only one checkbox at a time -->
    $(':checkbox').on('change', function (){  //when the value of a checkbox will change 
          var th = $(this), name = th.prop('name');  //Get the selected checkbox name
          if (':checked')) //check whether previously another checkbox is checked or not
              //If another checkbox is checked previously then, uncheck it. 
              $(':checkbox[name="' + name + '"]').not($(this)).prop('checked', false); 
    $(document).ready(function() {                       
            $("#btn").click(function()  //when the submit button is clicked by the user.   
                var favorite;        //declare a value which stores a value of selected checkbox.
                 //Identifying the selected element of checkbox.  
                $.each($("input[name='color']:checked"), function() 
                    favorite=$(this).val();   //Store the selected checkbox value in a variable.
             alert("My favourite color is: " + favorite); //Display the checkbox value in pop-up



    In above code we taken a three checkbox, User select only one checkbox among three of them. When user select one of the checbox and click on submit button then the value of the selected checkbox will pop-up.


 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: