8

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);
    }
}
llanato
  • 2,508
  • 6
  • 37
  • 59
  • 1
    [Possible duplicate.](http://stackoverflow.com/q/8707226/6188402) – Washington Guedes May 17 '16 at 23:52
  • Pretty sure that the data function is not working as you would expect. Im pretty sure jquery makes a copy/ref/thing of the data attributes so your changing that not the attr. If you look at the .data for the same element after you changed it you will see its changed but the html attr will remain the same. – Spaceman May 17 '16 at 23:57
  • 1
    You can find a good explanation here: http://stackoverflow.com/questions/36663690/jquery-prop-returns-undefined-while-attr-works-as-expected-for-data – The Process May 18 '16 at 00:02

3 Answers3

8

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.

Himmel
  • 3,629
  • 6
  • 40
  • 77
2

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.

Grant Mooney
  • 390
  • 8
  • 17
1

You can do something like this:

$("#usernameStatus").attr('data-valid','1'); 

Instead of ising .html() which returns inner content of an element .