Julien S Julien S - 4 months ago 9
Javascript Question

Getting a specific id using jquery

I've a code which is like that :

<div class="answer_id" value="1" name="false">
<input id="AsnwerAnswer1" type="checkbox" value="1" name="true"></input>
Answer 1

I've 4 answers that are like the code above, the only thing that change is the value in my div and the input id's.

When I click on a checkbox the selected checkbox get the value true :

$("input:checkbox").click(function() {
var thisChecked = $(this)[0].checked;
$("input:checkbox").attr('name', 'false');
$(this).attr('name', 'true');
$(this)[0].checked = thisChecked ? true : false;

When I click on the button to send the answer :


I would like to get the value of the div that contains the selected checkbox (the one who has its value at true).

What should I add to this :

var iReponseId = $(this).closest('.answer_id').attr('value');

By the way it would be really great if you could help me understand what the click function does.
According to me, this remove all the atrributes checked so I can only get one checkbox selected, this set the name to every checkbox to false expect for the one that is selected but I don't understand this :

$(this)[0].checked = thisChecked ? true : false;


I did this to get what I wanted :

$("input:checkbox").click(function() {
$("input:checkbox").not(this).prop('checked',false).removeAttr('class', 'chosen_answer');
$(this).attr('class', 'chosen_answer');

And then

var iReponseId = $('.chosen_answer').closest('.answer_id').attr('value');


In your code $(this)[0].checked = thisChecked ? true : false; is helps to rollbacks your previous state of checked property after removing the checked property, it can be reduced as this.checked = thisChecked.

You can reduce your entire code as follows

// use change event always for chekbox
$("input:checkbox").change(function() {
    // get all checkbox
         .not(this) // ignore the clicked checkbox
         .prop('checked',false) // uncheck the checkbox 
         .attr('name', 'false'); // set the attribute
    $(this).attr('name', 'true'); // set name of clicked 

For getting the div which contains the input, you need to use answer_id class not response_id.

var iReponseId = $(this).closest('.answer_id').attr('value');

FYI : While using custom attribute always use standard data-* format.