.attr("value") is always returning undefined? - javascript

I have a hidden element and within my jQuery:
<input type="hidden" id="1val" value="24">
var valID = $("#1val").attr("value");
However when I try to print valID it is always printed as undefined? What am I doing wrong?
Thanks

It's always safer to use the .prop() or .val() method to get the current value property:
var valID = $("#1val").val();
// or
var valID = $("#1val").prop("value");
As of jQuery version 1.9, the .attr() method will only get the element's attribute, which may not actually reflect the element's actual property.
According to the version 1.9 release notes, under .attr() versus .prop():
The value property versus attribute on input elements is another example of this ambiguity. The attribute generally reflects the value that was read from the HTML markup; the property reflects the current value. Since the .val() method is the recommended jQuery way to get or set the values of form elements, this confusion usually does not affect users.
However, when a selector like input[value=abc] is used, it should always select by the value attribute and not any change made to the property by the user, for example from them typing into a text input. As of jQuery 1.9, this behaves correctly and consistently. Earlier versions of jQuery would sometimes use the property when they should have used the attribute.
Under the hood, as of version 1.9, the .attr() method will only return the current attribute of the element (and not the property). The attribute and the property may not actually be the same. For instance, if there was initially no attribute on the element, and then the value was programatically set using a method such as .val(), then the attribute wouldn't have changed meaning that .attr('value') would return undefined.
As stated above, use the .prop() or .val() method in order to get the element's current value property.

Use $('#input-id').val(); to get value of input.

Related

jQuery data function returning the first value

I have a one span tag with data attribute, data-kr-id. On clicks of different items of the list, I update this span's data-kr-id attributes and it gets updated.
When for the first time I retrieve this(data-kr-id) value using jQuery's data method, I get the correct value. But from the subsequent time, I always get the same value as of the first time. But on using jQuery's attr function, I get the correct value. Can't figure out why.
CODE: Where I set the data-kr-id value:
$_applozicWtLauncherBtn.attr('data-kr-id', seller.UserId);
CODE: Where I retrieve the values:
var topicId = $applozic(this).data("kr-id");
topicId = $applozic(this).attr("data-kr-id");
In the above code where I retrieve values, using data method gives me old value(the value of the first item I retrieved), but using attr method gives me correct value.
UPDATE :
As informed by everyone, I was setting the data attributes with attr method and retrieving the value with data method. After using data method for setting the attribute, When I was retrieving the values, I was getting a getting empty string. After digging a bit deeper, I realized there are two different versions of the jQuery are being used here.
Sorry for the incomplete information and late update.
You set value only using attr, Second time when you set data-kr-id value using attr then data value remains same, so need to set value with data also
// With Attr
$_applozicWtLauncherBtn.attr('data-kr-id', seller.UserId);
// With Data
$_applozicWtLauncherBtn.data('kr-id', seller.UserId);
Actually jquery's .data() fetches value from the property (same as .prop()) not from attributes. Main difference is .attr() fetches data from HTML tag which you can see it will reflect on your HTML when you update it with .attr(). But when you use .prop() or .data() it will not reflect in HTML tag but it will update value in it's property for that HTML tag as per the DOM tree.
You'll find out more about difference property and attribute from here.
Initially this property will set when your element is created. So for the first time your .data() and .attr() will work fine. When you update value from .attr() it will manipulate DOM but property will be remain same.

jQuery find all elements with certain attribute and get the value of it

I need to get values of every existing 'ajaxify' attribute on the page.
$('[ajaxify]')
This gets me 361 objects. How to get the values?
To get all value as an array, use map(), attr() and get() methods
$('[ajaxify]').map(function() {
return $(this).attr('ajaxify')
}).get()
FYI : Always try to use data-*(eg :data-ajaxify) for custom attribute, since it's the standard way to use custom attribute. In than case you can use data() method to get attribute value.

How do I check an element is exists in JQuery?

I have to set a specific value to an element if the element is exists.
var a = jQuery("#abc");
if(a) {
a.val("something");
}
For this, I've to check a.length to check the element is exits.
What happen if I directly set the value without checking the element is present or not?
Because, If I do the following
jQuery("#abc").val("dfd");
I don't get any error in chrome when the element is not present. So, can I continue to use like this?
or
any workaround?
Help appreciated!
What happen if I directly set the value without checking the element is present or not?
Nothing. Calling jQuery methods on an empty jQuery object (set) doesn't cause a problem, it just does nothing. This is one of the great things about the set-based concept used in jQuery. The equivalent DOM code (document.getElementById("abc").value = "something";) would throw an error, but the jQuery version doesn't.
Specifically, if the jQuery set is empty:
Calling setter methods (like your val call) becomes a no-op.
Calling getter methods — for instance, var x = $("#foo").val(); — returns the value undefined.
Calling traversal methods — for instance, var divs = $("#foo).find("div"); — gives you a new empty set.
You only need to check (using if (a.length) as you said, or if (a[0])) if you actually care.
jQuery("#abc").val("dfd");
I don't get any error in chrome when the element is not present. So, can I continue to use like this?
Yup.
jQuery's val() method simply sets (or gets) the value of each matching element. If there are no matching element, there will be no value to set (or get). You don't need to check if the element exists first.
From jQuery's val() documentation:
Description: Set the value of each element in the set of matched elements.
If there are no matched elements, nothing will happen.
Try with -
jQuery("#abc").length > 0
Yes, you can safely continue. JQuery just executes a function on all elements found by the selector - if there are none, it does nothing. There's no error.

Attribute value VS property value

I have an <input> element which is loaded with a default value. Later on, i change that value via jQuery's input.val("different value").
When I console.log() the element, I see this in firebug:
Object[input.cs_required.form-control.input-sm property value = "12/29/2014" attribute value = "12/02/2014"]
Why are there two different values assigned to the input?
What is the
difference between the property value and the attribute value?
Should
I be concerned?
Quick example of the difference:
jQuery('#something').val() changes the *.value property.
jQuery('#something').attr('value','neValue') changes the attribute on that component.
There is an important difference between the two. Take a look at this for more info.
What's the difference between jQuery .val() and .attr('value')?
The only thing you have to worry about is whether you are using/assigning/utilizing the correct item - property or attribute.
As you said, you are providing a default value via the value HTML attribute. That will be the initial value of the DOM element's value property. Changing the propery does not affect the attribute.
The value of HTML attributes is often used as initial value for the corresponding DOM property.

Do the property names in JQuery have different names?

I once saw a text about Jquery stating that in Jquery some properties have different names. I think it was the value property that is accessed in Jquery as val or something like that. Does JQuery do this a lot? Is a common practice of Jquery to change properties names?
jQuery does not change any property names.
jQuery implements it's own methods on jQuery objects. Those are completely separate from DOM properties or DOM methods.
For example, you can retrieve the value of any input control from a jQuery object using the .val() method. Internally, the .val() method on the jQuery object accesses the contents of the DOM object (perhaps using the .value property), but it is not replacing that DOM property in any way. It is still there is you choose to use it instead.
Similarly, jQuery has a .html() method that returns the innerHTML of an object. Again, this is jQuery method on a jQuery object and does not replace the DOM property innerHTML in any way.
Here are some code examples to illustrate:
<input id="test" type="text">
<div id="title">This is my Title</div>
Using plain javascript:
var text = document.getElementById("test").value;
var title = document.getElementById("title").innerHTML;
Using jQuery:
var text = $("#test").val();
var title = $("#title").html();
Notice that both the jQuery ways are method calls, not properties.
Even when using jQuery objects, you could get the DOM object out of the jQuery object using the .get(n) method and use the DOM property, though there usually isn't a reason to do so:
var text = $("#test").get(0).value;
var title = $("#title").get(0).innerHTML;
jQuery doesn't change property names. jQuery returns jQuery instances not dom elements.
If you do $thing[0].value it will work. If you do $thing.prop("value") it will work.
If you use $thing.val(); which is jQuery's val method (which is "kind" of like val but does a bunch of weird edge case magic as well) then it will "probably" return the value of the wrapped dom element.
Not that I'm aware of, the case of val is because it let's you set or get the value of all form fields (textfields, radio buttons, checkboxes, textareas, etc.) something that's not possibly simply by doing input.value in all cases.

Categories