How to add values inserted using jquery .load() -
i have values inserting using jquery .load. want add together values , display result in div (or span or whatever). here code using insert values (numbers plain text):
above closing body tag: have:
$( "#result1" ).load( "mypage.php?f=15 .threadcount" ); $( "#result2" ).load( "mypage.php?f=16 .threadcount" ); $( "#result3" ).load( "mypage.php?f=25 .threadcount" ); $( "#result4" ).load( "mypage.php?f=18 .threadcount" );
and displaying values farther page using:
<div id="result1"></div>, <div id="result2"></div>... etc.
to add together them , show total i've tried using this reply "add values using jquery"
but gives me "$nan" total value. i'm assuming because it's loading value @ same time doing sum? or doesn't recognise bit of text coming in frm .load number?
i've tried alter code such used in this reply "dynamically adding sum of field in jquery" answer, adds values form inputs they're typed, i'm not getting anywhere either.
many advice can give.
all .load()
operations asynchronous. means finish sometime in future. have wait until done until can correctly calculate sum. add together illustration code how that.
var cnt = 0; function done() { --cnt; if (cnt <= 0) { // requests done // set code here calculate sum } } cnt = 4; $( "#result1" ).load( "mypage.php?f=15 .threadcount" , done); $( "#result2" ).load( "mypage.php?f=16 .threadcount" , done); $( "#result3" ).load( "mypage.php?f=25 .threadcount" , done); $( "#result4" ).load( "mypage.php?f=18 .threadcount" , done);
or, version using jquery promises:
function loadresult(target, query) { var def = $.deferred(); $("#result" + target).load("mypage.php?f=" + query + " .threadcount", function() { def.resolve(); }); homecoming def.promise(); } $.when(loadresult(1,15), loadresult(2,16), loadresult(3,25), loadresult(4,18)).then(function() { // calculate result here });
jquery load addition
No comments:
Post a Comment