Julien S Julien S - 6 months ago 15
jQuery Question

Uncheck a checkbox with conditions

I would like to make a survey on a website with a question and three possible answers.

The problem is that i'm having trouble with the check/uncheck, I want to have only one answer checked, so if the user clicks on an answer and he has already checked an other one, it keeps only the last one.

Here is what I've done :

$("input:checkbox").click(function() {
if($(this).is(':checked')){
var iSurveyId = $(this).closest('div').attr('name');
var iAnswerId = $(this).closest('p').attr('value');
var bIsChecked = 'true';


If the user click on a checkbox, I'll get the survey ID that is in the name of my div and the ID of my answer which is in my paragraph's name.

I'm using jQuery 1.1.12 so I can't use every function for exemple I can't use .prop().

Answer

You can use the input type radio instead of checkboxes so that all the user can only select one answer, or clear all the checkboxes first like this

$("input:checkbox").click(function() {
     $('input:checkbox').removeAttr('checked');
     $(this).attr('checked', 'checked');
}

The above should removed the checked attribute from all the select boxes and assign the checked attribute to the clicked one, or if you have multiple questions, each with multiple answers, you can put the checkboxes in a div and change the code to:

$("input:checkbox").click(function() {
    $('#div_id input:checkbox').removeAttr('checked');
    $(this).attr('checked', 'checked');
}