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>
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.val() method to get the value of a form input, not attr('value')id which is invalid. id must be unique within the DOM. Use classes if you want to group common elements.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)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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With