Émilie Robert
Émilie Robert

Reputation: 109

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

Upvotes: 0

Views: 40

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075189

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.

Upvotes: 1

Related Questions