Ben
Ben

Reputation: 1493

jQuery Set attr and then Get attr

I am creating a page that sets 2 attributes and then I am trying to reference those attributes after the page has loaded.

I have been able to set the attributes without a problem, I have also been able to reference the attributes if I hard code them into the credit and debit attributes.

But trying to call them dynamically isn't working. Open to suggestions.

<div class="net" credit="" debit=""></div>


$(document).ready(function() {
    ... some fancy code involving arrays and junk ...
    if(TYPE == 'credit') {
        $(".net").attr('credit',data.response.stats.total);
    } else if (TYPE = 'debit') {
       $(".net").attr('debit',data.response.stats.total);
    }
});

$(window).bind("load", function() {
    afterPageLoad();
});

function afterPageLoad(){
    total_credit = $(".net").attr('credit');
    total_debit = $(".net").attr('debit');
    total = (total_credit - total_debit);
    $(".net").html( "$"+total );
}

Upvotes: 3

Views: 263

Answers (4)

Shawn G.
Shawn G.

Reputation: 622

When grabbing the attributes for total_credit and total_debit you should use parseFloat();

ex: parseFloat( $(".net").attr('credit') );

you should also set a fallback in the case the attribute isn't set.

ex: total_credit = parseFloat($(".net").attr('credit')) || 0;

$(document).ready(function() {
    var TYPE = 'credit';
    if(TYPE == 'credit') {
        $(".net").attr('credit', 123);
    } else if (TYPE = 'debit') {
       $(".net").attr('debit', 53);
    }
});

$(window).bind("load", function() {
    afterPageLoad();
});

function afterPageLoad(){
    total_credit = parseFloat($(".net").attr('credit'))||0;
    total_debit = parseFloat($(".net").attr('debit'))||0;
    total = (total_credit - total_debit);
    $(".net").html( "$"+total );
}

Upvotes: 0

epascarello
epascarello

Reputation: 207511

The problem is the "... some fancy code involving arrays and junk ..."

data.response suggests you are making an Ajax call which is asynchronous and you are trying to read the attributes before they are set.

Put the logic in the callback of the Ajax call, do not call in the onload portion.

Upvotes: 1

Steve
Steve

Reputation: 8640

To read dynamic attribute values, you need to use prop() instead of attr().

Ideally, however you should store custom values in a data- attribute (i.e. data-credit) and then use jQuery's data() method to get/set the value.

Upvotes: 0

charlietfl
charlietfl

Reputation: 171669

Suggest using data- attributes that can be read by jQuery.data()

<div id="test" data-foo="bar"></div>

GET

alert( $('#test').data('foo'))

SET

$('#test').data('foo','new value, or object or array'))

The attributes don't have to exist to use this. You can store anything any time on an element, as well as read data in markup.

jQuery.data() API Docs

Upvotes: 3

Related Questions