How to make checkbox function like radio button

02nd, January 2018 By

Today we will check how make check box functional like radio button means like radio button we will able to click on one radio button in one time .As we are creating an online polling etc on website using check box so the user will able to click on only one check box not all.

checkbox function like radio

 

Today we will check how we will do that easily.Just using  Jquery we will make it very easy.You will see the working demo example from link below.

HTML

First create the HTML  where you want to make the functionality for check box like the radio buttons.We are in example creating a poll to check if you like webs expert or not.We will able to check on check box out of three yes,no and No Idea. If one selected out of three the other one automatically deselected.


<div id="main">
<form method="post">
  
<div id="answer1">

<h2> 1. Are you Like Webs Expert</h2>
 
      yes<input type="checkbox" name="youlike" value="Hourly" /> 
      No<input type="checkbox" name="youlike" value="Daily" />  
      No Idea<input type="checkbox" name="youlike" value="Weekly" />  
   </div>

<div id="answer2">
      
<h2>2. How good are Webs Expert </h2>


    
      Yes<input type="checkbox" name="good" value="Hourly" />  
      No<input type="checkbox" name="good" value="Daily" />  
      No Idea<input type="checkbox" name="good" value="Daily" />
   </div>

 </form>

</div>


JavaScript

Now the real magic for check boxes works here.If we select one check box another check box are deselected automatically.Thus on click of check boxes under the id ‘answer1’  we will removed the checked attribute from the other check boxes under the id  answer1.

$(document).ready(function(){

/* select answer 1 */
$("#answer1 input:checkbox").click( function () {
$("#answer1 input:checkbox").removeAttr("checked");
$(this).attr("checked","checked");
});

/* select answer 2 */
$("#answer2 input:checkbox").click( function () {
$("#answer2 input:checkbox").removeAttr("checked");
$(this).attr("checked","checked");
});
});

Hope this will help you.

Leave a Reply

Your email address will not be published. Required fields are marked *