jQuery data function returning the first value - javascript

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.

Related

Getting different results from attribute.dataset and jquery .data() method

I was getting unexpected results and when I debugged into the problem, I found that I was not getting right data-attribute value by Jquery .data() method. It was pretty clear that value was not right and when I changed my code to attribute.dataset.name (native property of an element) It returned me the expected value.
here's the screenshot of an error
Any ideas, what could be the possible reason because I am using a lot of data-attributes in my situation and don't want to change the code everywhere I am accessing data-attributes by Jquery .date() method.
.data(prop) and .dataset[prop] can be different if:
The HTML dataset contains one value
jQuery's .data has been called on the element previously to store a value associated with the same key
Example:
$('div').data('foo', 'newFooVal');
console.log($('div').data('foo'));
console.log($('div')[0].dataset.foo);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-foo="oldFooVal"></div>
jQuery's .data will retrieve:
Any previous value set with .data (which will be completely unrelated to the dataset)
If no previous value has been set to that key with that element, the value for that key in the dataset will be returned
So you have to be careful with what setting and retrieving. It's admittedly not entirely intuitive, since it'll do something different in different situations.

How to work with custom Custom data-* attributes [duplicate]

I am updating a data attribute by jQuery, Like:
jQuery('div').data('hidden', 'true');
alert(jQuery('div').data('hidden'));
Data attribute value got changed and returned new value which is true but DOM is still showing the old value which is false.
When you use .data() to update a data value, it is updating internal object managed by jQuery, so it will not be updated in the data-* attribute
I was beating around the bush so badly :( and able to solve the problem. Seams like we can't do achieve this using the jquery data method if the html is dynamic and the data attribute changed later after accessing the first time.
According to jQuery.data()
The data- attributes are pulled in the first time the data property is
accessed and then are no longer accessed or mutated (all data values
are then stored internally in jQuery).
So what I did is, changed it to attr method which won't give you the parsed value for integer, so you have to use '+' operand to convert like:
+ myElement.attr('data-index');
Note: You have to be careful, it will convert the result to NaN if there is any string in the data attr. BTW it's your choice of implementation of the code.

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

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.

Setting jQuery plugin options from data attributes

Im having a problem setting options to an array value in a jQuery plugin using data attributes.
If I reference the data attribute using a class selector
$('.tm-input').tagsManager(
{
prefilled: $('.tm-input').data('load')
})
It works but all the elements get the same values.
If I reference using "this" it sets the correct values but it comes across as a string not an array.
$('.tm-input').tagsManager(
{
prefilled: $(this).data('load')
})
I've tried using JSON.parse() but I get an error about an unexpected character. Any help would be appreciated!
Have you tried each
$('.tm-input').each (function () {
$(this).tagsManager( { prefilled: $(this).data('load') });
});
Explanation:
When a selector has more than 1 element, applying a method to it will typically affect all of the elements, but retrieving a property will typically only return that property from the 1st element.
So when you use .tagsManager on your $('.tm-input') selector, you are applying .tagsManger to all of the elements. But when you set prefilled:$('.tm-input').data('load'), the data method is only grabbing the data from the first element in the list, every single time.
When you use each, it applies the logic inside of the each block to each element individually, rather than all of them at once, so when you use $(this).data('load'), it grabs the load attribute from each individual element as well.

jquery attr() not returning expected value

I am using jQuery and would like to retrieve the 'id' attribute
of a clicked element, which in this case is a element.
Kindly check the image below. Notice that the returned string whenever
I use the attr() method in jQuery is somekind of an object (or array perhaps).
The expected value is printed below the next line. It returns the right value when
I use this:
$(this)[0].id
When an element is clicked, Isn't it the element is the one being reference in 'this'?
Why does attr() return an array?
I isolated the code and figured out that the tinymce plugin for jquery is making a conflict. Check out the static.html
https://www.dropbox.com/s/wbk8hxqjw34hzn1/jquery-attr-not-working.7z
Sorry for the archive, Dropbox won't let me upload 9mb and above so I have to compress.

Categories