Log in

View Full Version : attr() won't work on JQuery object



gib65
07-02-2013, 05:04 PM
Hello,

I'm retrieving an element on the page with JQuery and trying to get the "value" attribute like this:

var myVar = $("#elmId").attr("value");

but myVar ends up being "undefined".

I know I can get the element itself because this line works fine:

var myVar = $("#elmId");

Why doesn't attr() work?

jscheuer1
07-02-2013, 08:48 PM
Hard to say for sure without fiddling around a bit and/or seeing your page.

But I can tell you that's not how to get the value, and that technically speaking only form elements may have attribute values (they don't have to be in forms though), and that technically it's a property, not an attribute. It's both really, except that once the page is loaded, the attribute should remain the same regardless of user interaction and/or javascript effects, the property can be changed.

That all said, if what you have is a form element (input, select, textarea, radio button, checkbox), and it does have some value, here's how to get its value in jQuery:


var myVar = $('#elmid').val();

gib65
07-09-2013, 03:50 PM
Hard to say for sure without fiddling around a bit and/or seeing your page.

But I can tell you that's not how to get the value, and that technically speaking only form elements may have attribute values (they don't have to be in forms though), and that technically it's a property, not an attribute. It's both really, except that once the page is loaded, the attribute should remain the same regardless of user interaction and/or javascript effects, the property can be changed.

That all said, if what you have is a form element (input, select, textarea, radio button, checkbox), and it does have some value, here's how to get its value in jQuery:


var myVar = $('#elmid').val();

Thanks, but the problem I was having (which prevented any method from working) was that the script was being run before the DOM objects were available. The script was at the top of the page and it called my function (which included the code in the OP) before anything was loaded onto the page. Replacing the function call with:

$(document).ready(MyFunction);

did the trick. It says to call MyFunction() only when the page is ready.

jscheuer1
07-09-2013, 04:11 PM
Right, that would fall under the category of:


if what you have is a form element

You didn't. And under:


Hard to say for sure without fiddling around a bit and/or seeing your page.

But what I said about getting an element's value is still true. If you go for the attribute (.getAttribute('value') in javascript, .attr('value') in jQuery) you may come up with unexpected results in some browsers. In jQuery use .val(), in javascript use .value.