Checkbox value in field input hidden [duplicate]

3

I'm having a problem with jQuery checkbox manipulation. I have several fieldsets with checkboxes, and I want that when the person clicks on a check the check value is added to the input hidden of each fieldset.

I wanted to know how I get this value from the check that was clicked.

var text1 = document.getElementById("text1");
var text  = document.getElementById("text2");

$("#radios1 .check").click(function () {
    text1.value = $(this).val();
    $(this).attr("checked");
    alert(text1.value);
});
<fieldset id="radios1">
<input class="check" type="checkbox" value="1"> <br />
<input class="check" type="checkbox" value="2">
<input type="hidden" id="text1" value="1" />

</fieldset>

<fieldset id="radios2">
<input class="check" type="checkbox" value="1"> <br />
<input class="check" type="checkbox" value="2">
<input type="hidden" id="text2" value="1" />
</fieldset>

I made a JSFIDDLE with what I have so far: link

Does anyone know how to proceed?

    
asked by anonymous 05.01.2016 / 15:57

1 answer

2

You can do this:

$('fieldset[id^="radios"] .check').click(function() {
  $(this).closest('fieldset').find('input:hidden').val(this.value);
});

The fieldset[id^="radios"] selector selects all fieldset whose ID starts with radios .

Then, inside the function you can use .closest() to go to fieldset where this element is and then go look for that input hidden with .find() .

In this way, it does not matter in the IDs of the elements, it works with N equal pieces.

jsFiddle: link

    
05.01.2016 / 16:05