Checkbox value in Hidden input field

Asked

Viewed 456 times

3

I have a problem with checkbox manipulation with jQuery. I have several fieldsets with checkboxs, and I want when the person clicks on a check the check value is added to the Hidden input of each fieldset.

I was wondering how I got this check value 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 did a JSFIDDLE with what I have so far: https://jsfiddle.net/ejb5mgoy/

Does anyone know how to proceed?

  • Will be added (type summed ?), will be added (type separated by comma), or will the value be updated by the last click?

1 answer

2

You can do it like this:

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

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

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

This way does not interfere with the Ids of the elements, it works with N equal pieces.

jsFiddle: https://jsfiddle.net/qcnq1dyz/

  • Good! Thanks for the help.

  • Dude, I had a problem. When I put it on a table, it doesn’t work.

  • @Luangabriel which element contains both the checkbox and the input:Hidden?

  • @Luangabriel shows the new HTML you have to help you use my answer

  • Here’s what I have now, https://jsfiddle.net/qcnq1dyz/1/, except for the table your code works 100%. But inside I can’t access. I’m kind of a layman in JS, suffering.

  • @Luangabriel this HTML is invalid. You are mixing fieldset in the middle of the table. What’s the idea of using fieldset? you can’t use a class in tr for example? HTML comes from where?

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.