Get Wrong Value in Data Attribute Jquery

JQuery data function returns the wrong value

There is a different between the jQuery's data function and the attr function.
The data function is binded to the element (not necessary to the data attribute). If an element has data-X='val' you can use both jquery's data function and the attr function to get the value:

$('el').data('X')
$('el').attr('data-X')

However - in case you change the data (using the data(...) function) - to get the new value you must use the data function (this change will not affect the value of the attribute), and the opposite is the same - if you change the value using the attr function - it will not affect the values of the data() function.

Here is an example:

$(function() {  $('#btn1').click(function() {    console.log('value using data function: ' + $('#d1').data('name1'))    console.log('value using attr function: ' + $('#d1').attr('data-name1'))  });  $('#btn2').click(function() {    $('#d1').data('name1', 'new value - using data');  });  $('#btn3').click(function() {    $('#d1').attr('data-name1', 'new value - using attr');  });});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div id="d1" data-name1="abc"></div><button id="btn1">Get Values</button><br /><button id="btn2">Change Values using data function</button><br /><button id="btn3">Change Values using attr function</button><br />

Getting different results from attribute.dataset and jquery .data() 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>

get data attribute and set new value

$("flipUpMenuBox") need to be $("#flipUpMenuBox")

Working snippet:-

$( document ).ready(function() {  var btnFlip = $("#flipElement");  var flipUpElement = $("#flipUpMenuBox");  btnFlip.click(function(){    if(flipUpElement.attr('data-flip') == 'false'){ // use ==      flipUpElement.attr('data-flip','true');    }else{      flipUpElement.attr('data-flip','false');    }  });});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="flipUpMenu" id="flipUpMenuBox" data-flip="false"></div><button id="flipElement">Flip Up </button>

Changed data attribute not recognized in jquery selector

While you have your answer, I don't think the essential point has been made in any of the answers so far, and that is that the binding of an event handler must happen after the target element exists.

When you try to bind an event handler to a particular element in the DOM, the element must exist at the time. If it does not exist, the handler has nothing to bind to, and so the binding fails. If you later create the element, it's too late, unless you re-run the binding statement.

It will soon become second nature to call appropriate event handler binding statements after you create a new element (by modifying the HTML using javascript) that needs a handler.

For instance, in my current project I regularly make AJAX calls to a server to replace blocks of HTML as things happen on the page. Even if some of the new elements are exactly the same as the ones being replaced, they will not inherit any bindings from the replaced elements. Whenever I update the HTML I call a function that contains necessary statements to bind my event handlers to the new copy of the active elements.

Your code would work if you made the following change:

$('body[data-page="first"] .start').on('click',function ()
{
body.attr('data-page','second');
$('body[data-page="second"] .start').on('click',function (){
console.log('Test');
});
})

A couple of other (off-topic, but related) points:

  • It's possible to bind a handler to an element multiple times. The trick to avoiding this is to include the .off() method in the chain before binding (noting though that .off("click") will unbind all click handlers bound to that element, not just yours) e.g.

    $("#mybutton").off("click").click(function(){myHandler()});

  • "the arrow function doesn’t have its own 'this' value" () so don't use arrow functions in event handlers if you plan to reference any of the element's properties via 'this'. e.g.

    $("#mybutton").off("click").click(() => {console.log(${this.id})}); // >> "undefined"

Unable to get data attribute value in jquery using PHP

Simply you can use on keypress with class postcmnt or with input

$('.postcmnt').on('keypress', function(e) {
var code = e.keyCode || e.which;
var _t = $(this);
if(code==13){
var valss=_t.data('vals');
var inputVal=_t.val();
alert('attribute value is '+valss);
alert('input value is '+inputVal);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' name='postcmnt' class='postcmnt' value='abc' data-vals='123'/>

jQuery $.data() not returning correct value when data attribute is updated

You should set data using .data()

$('#submit').data('price',$(this).val());

Demo ---> http://jsfiddle.net/gv5cR/2/



Related Topics



Leave a reply



Submit