Reputation: 152
I have an xml file and I want to search some values from that file using jquery but the value that i get inside the function and outside the function are different please point me in the right direction.this is the xml file
<?xml version="1.0" encoding="UTF-8"?>
<plist version="1.0">
<dict>
<key>ID</key>
<string>B0A6EF3C-221F-4918-89C2-340B05F6A7AD</string>
<key>Name</key>
<string>name</string>
<key>Items</key>
<array>
<dict>
<key>Mode</key>
<integer>1000</integer>
<key>background</key>
<string>RGBA:0.000000,1.000000,1.000000,1.000000</string>
<key>Enabled</key>
<true/>
</dict>
<dict>
<key>Mode</key>
<integer>1000</integer>
<key>background</key>
<string>RGBA:0.000000,1.000000,1.000000,1.000000</string>
<key>Enabled</key>
<true/>
</dict>
</array>
</dict>
</plist>
the code that i used is
$.post("demo.xml",{},function(xml){
$('array',xml).each(function(i) {
$(this).find('dict').each(function(){
var valueError = findvalue($(this),'Mode');
alert(valueError);
});
});
});
function findvalue(tag,searchkey)
{
$(tag).find('key').each(function(){
key = $(this).text();
value = $(this).next().text();
//alert("inside = "+ value)
if(key == searchkey)
{
alert("key = "+key + " searchkey = " + searchkey +" value = " +value)
return value;
}
else
{
return "No Match";
}
});
}
when control inside the findvalue function it print correct value but when it going to Calling function and print the return value that is in this case is valueError it print undefined
Upvotes: 0
Views: 1342
Reputation: 24406
It's returning undefined because you are returning the value from inside a callback function, so the main function itself is not returning a value.
You'll need to set the return value to a variable in the function and return that from the main function:
function findvalue(tag, searchkey) {
var returnValue = false;
$(tag).find('key').each(function(){
key = $(this).text();
value = $(this).next().text();
if(key == searchkey) {
alert("key = " + key + " searchkey = " + searchkey + " value = " + value);
returnValue = value; // assign to the parent functions variable
return value; // only returns to the callback function
} else {
returnValue = "No Match"; // same as above
return "No Match";
}
});
return returnValue; // this will allow you to access that value now
}
It seems strange to me to return 'No Match' during a loop, perhaps you should look at simply removing that else statement and letting the parent function simply return false
(default as defined at the top) when no match is found, and output "No Match" when you display the results (presumably where you are outputting the results of findvalue()
).
Upvotes: 1