Saturday 15 September 2012

javascript - Find value in - from ajax -



javascript - Find value in <li> from ajax -

i calling ajax via function. when ajax has been completed, unable find value in <li>

a function utilize ajax:

function findlist(postcode) { $.getjson("/list/" + postcode, function(data) { if (data.length > 1) { $.each (data, function (index, element) { if (element != "address") { $('#order-list-form').append($("<li></li>").attr("value",data[index].value).text(data[index].name)); } }); } }); }

if page loaded, find value $("#postcode").val() , execute findlist(), 1 time has been completed, need find value dus123 in <li> has been populated via ajax , add together class selected-address - don't seem work.

if ($("#postcode").val() != "") { // execute ajax findlist( $("#postcode").val() ) // not working here // when ajax completed, want find find value in <li> , add together class selected-address $("#order-list-form li").find('value="dus123").addclass("selected-address"); }

the selector in phone call find not valid. search attributes, need wrap them []:

$("#order-list-form li").find('[value="dus123"]').addclass("selected-address");

however, since you're setting attribute straight on li element itself, need find attribute on element, not on kid element above selector doing:

$('#order-list-form li[value="dus123"]').addclass("selected-address");

another issue due way requests sent , processed ajax, line of code run before ajax request has completed, , before element has been appended document. prepare have 2 options. quick , dirty way, create ajax request synchronous, i'll leave research getjson , ajax methods find out how do.

the second, , more right way, either run line of code within success function in phone call getjson:

function findlist(postcode) { $.getjson("/list/" + postcode, function(data) { if (data.length > 1) { $.each (data, function (index, element) { if (element != "address") { $('#order-list-form').append($("<li></li>").attr("value",data[index].value).text(data[index].name)); } }); } $('#order-list-form li[value="dus123"]').addclass("selected-address"); }); }

or can allow findlist function take callback, , utilize that:

function findlist(postcode, callback) { $.getjson("/list/" + postcode, function(data) { if (data.length > 1) { $.each (data, function (index, element) { if (element != "address") { $('#order-list-form').append($("<li></li>").attr("value",data[index].value).text(data[index].name)); } }); } callback(); }); } if ($("#postcode").val() != "") { findlist( $("#postcode").val(), function() { $('#order-list-form li[value="dus123"]').addclass("selected-address"); }); }

javascript jquery ajax

No comments:

Post a Comment