Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery .attr or .prop to set attribute value not working

I've created a button with an attribute named 'loaded' and initial value of 'no'. Upon clicking the button I'm running some ajax and at the very end of it I'm trying to set the 'loaded' attribute to 'yes' so that the ajax is not run again if the user clicks on the button more than once.

I have something like this: http://jsfiddle.net/PDW35/2/

Clicking the button does not change loaded to 'yes'. However, if you do an alert right after the .attr call like this:

alert($(this).attr('loaded'));

The alert box does contain 'yes' which doesn't help because once the user clicks, the same code above puts up a 'no' alert box on the screen.

It all behaves the same way if I use .prop() instead of .attr(). Am I missing a point here or .prop() and .attr() just don't work with custom attributes?

EDIT: Updated jsfiddle using ajax based on the comments below: http://jsfiddle.net/PDW35/5/

like image 367
mmvsbg Avatar asked Aug 01 '13 07:08

mmvsbg


People also ask

How set value to data attribute in jQuery?

The attr() method in jQuery is used to set or return the attributes and values of the selected elements.

Is jQuery attr deprecated?

jQuery deprecated (version 1.6) and removed (version 1.9) the use of . attr() for use to set "checked" and "disabled" properties. It also points out that attempting to retrieve values by using . attr() will result in confusion/problems, as in this example: $elem.

Which jQuery function can return the value of an attribute?

The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.


1 Answers

I am not exactly sure of the reason why the original code isn't working, but the $this seems to be the cause for some reason. Try the below and it seems to work. Fiddle is here.

I will try to update the answer with the reason as soon as I find it.

var loaded = $(".preview-button").attr('data-loaded');
if (loaded === "no") {
    $.ajax({
        success: function (result) {
            $(".preview-button").attr('data-loaded', 'yes');
            alert($(".preview-button").attr('data-loaded'));
        }
    });
} else {
    alert("data loaded");
}

Refer this thread and this seems to be the reason why the $this doesnt seem to work from inside the AJAX call.

like image 129
Harry Avatar answered Sep 22 '22 12:09

Harry