Émilie Robert Émilie Robert - 3 months ago 12
jQuery Question

jQquery Get dom modified attribute value

Let's say I modify an attribute value on click with a function like:

$('#dd ul.dropdown li a').click(function(e) {
var txt = $(e.target).html();
var langs = $(e.target).text();
$('#dd .currentlangs').html(txt);
langs = langs.trim().toLowerCase().replace(/\s+/g, "-");
$('.currentlangs').attr('data-lang', langs);
});


And then I want the current attribute value in a keyup function like:

var $input = $('#querysearch');
var dict = $('.currentlangs').attr('data-lang');
$input.on('keyup', function () {
alert(dict);
});


Needed value is "dict" variable but doing that I keep getting the initial value when DOM has been loaded. How can I get the current attribute when the keyup function is fired?

Thanks a lot

Answer

You're getting the value of the attribute as of when this line

var dict = $('.currentlangs').attr('data-lang');

runs. That's before the use clicks anything, so naturally you get the value as defined in the HTML. Move it into the keyup handler:

var $input = $('#querysearch');
$input.on('keyup', function () {
   var dict = $('.currentlangs').attr('data-lang');
   alert(dict);
});

...so that you get the value when the keyup event occurs.

Comments