Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery, data() not updating data attribute [duplicate]

I have the below piece of HTML and the associated jQuery. The htmlfunction is working correctly but the data function isn't affecting the HTML at all, I can't for the life of me figure it out, no errors in the browser at all.

HTML

<span id="usernameStatus" data-valid="0">x</span>

jQuery

data is returned by an AJAX call, it will only ever be true or false.

function validUsername(data)
{        
    if (data === 'true') {
        $("#usernameStatus").html("y").data("valid", 1);
    } else {
        $("#usernameStatus").html("x").data("valid", 0);
    }
}
like image 412
llanato Avatar asked May 17 '16 23:05

llanato


2 Answers

Per jQuery API Docs

The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.

The .data() method will not modify the existing DOM node, but will only be retrievable via calling of $selector.data(). Your DOM elements don't change, just the data attached to them.

like image 136
Himmel Avatar answered Nov 14 '22 07:11

Himmel


The .data() method does not modify the DOM element's attribute. However, data is still saved via. $selector.data( key, value ); and can be retrieved via. $selector.data( key );

In order to add an attribute to a DOM element, you will likely want to use the .attr() method. With .attr(), an attribute can be attached to an element via. $selector.attr( key, value ); and can be retrieved via. $selector.attr( key );

    validUsername(data) {       
        if (data === 'true') {
            $("#usernameStatus").html("y").attr("data-valid", 1);
        } else {
            $("#usernameStatus").html("x").attr("data-valid", 0);
        }
    }

JSFiddle example

One of the advantages of using .attr() instead of .data() is the ability to find all elements with an attribute (and value) via. the $('[key="value"]') selector.

like image 24
Grant Mooney Avatar answered Nov 14 '22 05:11

Grant Mooney