user1809790
user1809790

Reputation: 1369

Get value of checkbox by name

I need to get the value of a checkbox by name. I have the following code:

<input type="hidden" name="my_checkbox" value="0">
<input type="checkbox" name="my_checkbox" id="my_checkbox_id" value="1"  />

The idea is that if the checkbox is not checked, I would get the value of the input type hidden (which is 0).

Here is what I have tried but did not work:

$('input[name=my_checkbox]').val();

However this returned the value of both the hidden input and checkbox. Can anyone tell me how I can get the value of the checkbox when checked (1) or else get the value of the hidden input (0) when unchecked? I guess this has to be done by name so that if the checkbox is unchecked, I get the value of the hidden input as if the checkbox is unchecked you won't get its value.

Upvotes: 3

Views: 20747

Answers (5)

Arslan Butt
Arslan Butt

Reputation: 795

<input type="hidden" name="my_checkbox" value="0">
<input type="checkbox" name="my_checkbox" id="my_checkbox_id" value="1"  />

Try this it worked for me:

$( 'input[name="my_checkbox"]:checked' ).val();

Upvotes: 3

Roko C. Buljan
Roko C. Buljan

Reputation: 206121

Actually you don't need the hidden one, you just need to say:
if checkbox is not checked set his value to '0'
and this is all you need:

$('input:checkbox').not(':checked').val(0);

Upvotes: 1

Jai
Jai

Reputation: 74738

just find the :visible checkbox:

$('input[name="my_checkbox"]:visible').change(function() {
  if ($('input[name="my_checkbox"]:visible').is(':checked')) {
    alert($('input[name="my_checkbox"]:visible').val());
  } else {
    alert($('input[name="my_checkbox"]:hidden').val());
  }
});

tryout the fiddle: http://jsfiddle.net/JgzGa/1/

Upvotes: 1

ATOzTOA
ATOzTOA

Reputation: 35950

Why don't you do this:

if($("#my_checkbox_id").is(':checked')) {
    output = $("#my_checkbox_id").val();
} else {
    output = $('input[type=hidden]').val();
}

Upvotes: 1

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

You could add a new function for it:

$.fn.checkboxVal = function() {
    var checked = $(this).filter("[type=checkbox]:checked");
    if (checked.length)
        return checked.val();

    return $(this).filter("[type=hidden]").val();
};

Then you can say $("input[name=foo]").checkboxVal() and it'll get you the correct value.

Untested, so fixing any bugs is left as an exercise for the reader.

Upvotes: 0

Related Questions