Sreyas MN
Sreyas MN

Reputation: 49

How Can i retrive the attribute value of a checkbox using javascript

How can we retrieve the attribute values of a checkbox using javascript.

I am using a javascript function in onclick() event.

In that function i can able to identify the checkbox is checked or not.

But when i access to retrive value,i didn't get.

var id=$("#chkbox").attr("attibteid");

The above query wont return anything. Please suggest

Upvotes: 0

Views: 91

Answers (3)

Travis J
Travis J

Reputation: 82267

Hard to tell exactly what you are looking for here, in general if you have a checkbox

<input type="checkbox" 
       id="mycheckbox" 
       value="something" 
       attibteid="custom" 
       data-msg="hello" />

and you click on a button to look at it

<input type="button" id="btn" value="I check checkbox" />

then here are values you can check

$("#btn").click(function(){
 var $checkbox = $("#mycheckbox");
 var theValue = $checkbox.val();//"something"
 var theId = $checkbox[0].id;//"mycheckbox"
 var isChecked = $checkbox.is(":checked");//false or true
 var attrValue = $checkbox.attr("attibteid");//"custom"
 var someData = $checkbox.data("msg");//"hello"
});

demo

Upvotes: 3

Arseni Mourzenko
Arseni Mourzenko

Reputation: 52311

If you do get the check box status through the click event with $(this).is(":checked") but are unable to get it with $("#chkbox").is(":checked"), verify that:

  • The checkbox has an attribute id with the value chkbox,

  • That there are no other elements with the same id.

If you're looking not for the check status, but a value of an attribute, just do:

$("#chkbox").attr("<name here>")

where you replace "<name here>" by the actual name of the attribute you're looking for.

Upvotes: 0

Kevin Brechb&#252;hl
Kevin Brechb&#252;hl

Reputation: 4727

You can get the value of a checkbox like this:

var value = $("#chkbox").val();

Upvotes: 0

Related Questions