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);
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With