Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to get the value of a checkbox using Jquery

Tags:

jquery

I am new to Jquery and I am trying to fetch the value of a checkbox using attr(). But the result in the alert box says "undefined". Plz someone explain why does that happen?

$("#checkbox").click(function() {
  alert($("checkbox").attr("value"));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox" id="checkbox" value="UK">UK
<input type="checkbox" name="checkbox" id="checkbox" value="US">USA
<input type="checkbox" name="checkbox" id="checkbox" value="Rus">Russia
<div id="result"></div>
like image 630
Don'tDownvoteMe Avatar asked Dec 06 '25 14:12

Don'tDownvoteMe


2 Answers

You have several issues here:

  • $('checkbox') isn't a valid selector as it's searching for a <checkbox /> element which doesn't exist. You can select the element by attribute instead, eg [name="checkbox"] or by using the :checkbox selector.
  • You should use the val() method to get the value of a form input, not attr('value')
  • You have multiple elements with the same id which is invalid. id must be unique within the DOM. Use classes if you want to group common elements.
  • Use the change event on checkbox and radio inputs as it's better for accessibility (ie. it will still work for those users who navigate the web via their keyboard only)
  • Use the this keyword within the event handler to get a reference to the element which raised the event.

With those issues in mind, this should work for you:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox" value="UK">UK
<input type="checkbox" name="checkbox" value="US">USA
<input type="checkbox" name="checkbox" value="Rus">Russia
<div id="result"></div>

<script>
  $(":checkbox").change(function() {
    console.log($(this).val());
  })
</script>
like image 153
Rory McCrossan Avatar answered Dec 08 '25 19:12

Rory McCrossan


ID's should be unique, so don't use them in this case. But e.g. you can select all checkboxes:

$("input[type=checkbox]").click(function() {
  alert($(this).attr("value"));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox" id="checkbox" value="UK">UK
<input type="checkbox" name="checkbox" id="checkbox" value="US">USA
<input type="checkbox" name="checkbox" id="checkbox" value="Rus">Russia
<div id="result"></div>

I have also changed the inside of the alert, as click sets the this value to the affected element.

like image 41
meskobalazs Avatar answered Dec 08 '25 18:12

meskobalazs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!