Hi i tried to access a variable as follows,
for(var k=0;k<resultSet.length;k++)
{
alert(resultSet[k]);
$.get('/api/TagsApi/ElementsTagsIntersect?ids='+resultSet[k], function (data) {
testingarr = [];
for (var i = 0; i < data.length; i++) {
testingarr.push(data[i]["ID"]);
}
for (var w = 0; w <3; w++) {
if (($.inArray(testingarr[w], selectedloc)) > -1) {
var str = "<input type='checkbox' name ='test[]' value='" + resultSet[k] + "'/>" + resultSet[k] + "</br>";
$('#childs').append(str);
alert(resultSet[k]);
break;
}
}
}, 'json');
where first alert displays the exact value what i am expecting but when it comes to the inner for loop, alert returns undefined and adds a check box with undefined side to it.. i think i am using the proper initializations but confused why it does so?
The reason is that k changes value, so by the time the inner function gets called, k is already equal to resultSet.length. You can wrap the whole thing in another function and pass k as a parameter to bind it to a new variable that won't change with the original k:
for(var k=0;k<resultSet.length;k++)
{
(function (result) {
$.get('/api/TagsApi/ElementsTagsIntersect?ids='+result, function (data) {
var testingarr = [];
for (var i = 0; i < data.length; i++) {
testingarr.push(data[i]["ID"]);
}
for (var w = 0; w <3; w++) {
if (($.inArray(testingarr[w], selectedloc)) > -1) {
var str = "<input type='checkbox' name ='test[]' value='" + result + "'/>" + result + "</br>";
$('#childs').append(str);
break;
}
}
}, 'json');
})(resultSet[k]);
}
Related
I have a subtotals function that does some calculations on an html table (sums up columns that have assigned classes). I have modified it so that I can pass arguments to it, and on the first function call it works as desired. When I call it again it creates the cell and assigns the class, but the math or apparently something else is wrong because it is returning NaN. Here is my JSFiddle and below is my function. Any help would be appreciated!
//v is parent,z is child element,w is which child column....ex: 0 or 1, y is first run or not, z is class name you want assigned
function subtotals(v, w, x, y, z) {
$(v).each(function (index, element) {
var subTotalAmt = 0;
var numRows = parseInt($(this).attr("rowspan"));
var firstRow = $(this).parent();
var lastRow = firstRow.nextAll('tr').slice(numRows - 2, numRows - 1);
var currentRow = firstRow;
for (i = 0; i < numRows; i++) {
subTotalAmt += parseInt($(currentRow.children(w)[x]).text());
currentRow = currentRow.next("tr");
}
if(y == 'yes'){
lastRow.after('<tr><td class="sub0">Sub Total</td><td class="' + z + '">' + subTotalAmt + '</td></tr>');
$(this).attr('rowspan', numRows + 1);
}
else {
lastRow.append('<td class="' + z + '">' + subTotalAmt + '</td>');
}
});
}
$(function doSubtotals() {
subtotals('.parent','.child','1','yes','sub1');
subtotals('.parent','.child','2','no','sub2');
});
Some of your <td> are not containing a valid number , which case the calculation to fail and put NaN (stands for 'Not a Number') instead of a valid number (NaN + number = NaN).
To fix this i added this condition to your code :
for (i = 0; i < numRows; i++) {
var tdValue=0;
if(!isNaN(parseInt($(currentRow.children(w)[x]).text())))
{
tdValue=parseInt($(currentRow.children(w)[x]).text());
}
subTotalAmt += tdValue;
currentRow = currentRow.next("tr");
}
I've called some data from php using AJAX, and the result if I code alert(data.a) looks like this...
({a:[{my_id:"34", name:"Dave"}, {my_id:"39", name:"Barry"}]}
I'm not sure how to loop through this to extract the values.
My latest code...
for (var key in data.a)
{
if (data.a.hasOwnProperty(key))
{
alert(key + " -> " + data.a[key]);
}
}
... displays
0 -> [object Object]
and this displays the same too...
for (var i=0, tot=data.a.length; i < tot; i++)
{
for (var key in data.a[i])
{
if (data.a[i].hasOwnProperty(key))
{
alert(key + " -> " + data.a[i][key]);
}
}
}
What's the trick to looping through these results to extract the data for display?
If it helps, here's what I send at the end of my php...
$x['a'] = $myArray;
echo json_encode($x);
Thanks for your time and help.
Are you after something like this? Loop through all the objects the print out all of their properties and values?
for (var i = 0; i < data.a.length; i++) {
var objectInArray = data.a[i];
var keys = Object.keys(objectInArray);
for (var j = 0; j < keys.length; j++) {
var key = keys[j];
alert(key + " -> " + objectInArray[key]);
}
}
When you are doing data.a[key] in for loop, you are getting a json object: {my_id:"34", name:"Dave"} for key = 0, and {my_id:"39", name:"Barry"} for key = 1. So in order to get values you should do something like this:
for (var key in data.a)
{
if (data.a.hasOwnProperty(key))
{
alert(key + " -> " + data.a[key].my_id);
// data.a[key].name to get name attribute
}
}
Is it just
for (var i=0; i < data.a.length; i++) {
alert(data.a[i].my_id + " -> " + data.a[i].name);
}
In your example, data.a is an array of objects, so this would work:
for (var i = 0; i < data.a.length; i++) {
console.log('my_id: ' + data.a[i].my_id);
console.log('name: ' + data.a[i].name);
}
Today , i have been read all the topic about this but couldn't come up with a solution that's why i am opening this topic.
This is my function which creates the view and i am trying to have a onclick function which should directs to other javascript function where i change the textbox value.
<script type="text/javascript">
$('#submitbtnamazon')
.click(function(evt) {
var x = document.getElementById("term").value;
if (x == null || x == "" || x == "Enter Search Term") {
alert("Please, Enter The Search Term");
return false;
}
listItems = $('#trackList').find('ul').remove();
var searchTerm = $("#term").val();
var url = "clientid=Shazam&field-keywords="
+ searchTerm
+ "&type=TRACK&pagenumber=1&ie=UTF8";
jsRoutes.controllers.AmazonSearchController.amazonSearch(url)
.ajax({
success : function(xml) {
$('#trackList')
.append('<ul data-role="listview"></ul>');
listItems = $('#trackList').find('ul');
html = ''
tracks = xml.getElementsByTagName("track");
for(var i = 0; i < tracks.length; i++) {
var track = tracks[i];
var titles = track.getElementsByTagName("title");
var artists = track.getElementsByTagName("creator");
var albums = track.getElementsByTagName("album");
var images = track.getElementsByTagName("image");
var metaNodes = track.getElementsByTagName("meta");
//trackId ="not found";
trackIds = [];
for (var x = 0; x < metaNodes.length; x++) {
var name = metaNodes[x]
.getAttribute("rel");
if (name == "http://www.amazon.com/dmusic/ASIN") {
trackId = metaNodes[x].textContent;
trackIds.push(trackId);
}
}
for (var j = 0; j < titles.length; j++) {
var trackId=trackIds[j];
html += '<div class="span3">'
html += '<img src="' + images[j].childNodes[0].nodeValue + '"/>';
html += '<h6><a href="#" onclick="someFunction('
+trackId
+ ')">'
+trackId
+ '</a></h6>';
html += '<p><Strong>From Album:</strong>'
+ albums[j].childNodes[0].nodeValue
+ '</p>';
html += '<p><Strong>Artist Name:</strong>'
+ artists[j].childNodes[0].nodeValue
+ '</p>';
html += '<p><Strong>Title:</strong>'
+ titles[j].childNodes[0].nodeValue
+ '</p>';
/*html += '<p><Strong>Created:</strong>'
+ releaseDate
+ '</p>';*/
html += '</div>'
}
}
//listItems.append( html );
$("#track").html(html);
$("#track").dialog({
height : 'auto',
width : 'auto',
title : "Search Results"
});
// Need to refresh list after AJAX call
$('#trackList ul').listview(
"refresh");
}
});
});
</script>
This is my other function where i change the textbox value. it works actually with other values e.g. when i give hardcoded string value. I can see the value in the console but for some reason it gives me the error like :
here the string starts with B is AsinId where i take from amazon. I am definitely in need of help because i am totally stucked.
Uncaught ReferenceError: B00BMQRILU is not defined 62594001:1 onclick
<script type="text/javascript">
function someFunction(var1) {
tracktextbox = document.getElementsByName("trackId");
for (var i = 0; i < tracktextbox.length; i++) {
tracktextbox[i].value = var1;
}
$('#track').dialog('close');
}
</script>
The problem is '<h6><a href="#" onclick="someFunction('+trackId+ ')">', from the error it is clear that trackId is a string value, so you need to enclose it within "" or ''. So try
'<h6><a href="#" onclick="someFunction(\'' + trackId + '\')">'
I have the following two function in my code, the addValueToSTorage has to read the editable table data and add the values to the localStorage and the populate table reads the values from localStorage and populates the table with the updated values and makes the table non-editable.
function addValueToStorage() {
localStorage.clear();
var table = document.getElementById('table');
var i;
var j;
var rowLength = table.rows.length;
for (i = 0; i < rowLength; i++) {
var value=[];
for (j = 0; j < 4; j++) {
value.push(table.rows[i].cells[j].firstChild.data);
}
var val=JSON.stringify(value);
var key = "xyz" + localStorage.length;
localStorage.setItem(key, val);
}
populatetable();
}
function populatetable() {
$('#table').empty();
var header = "<tr><th>Select</th><th>Name</th><th>1</th><th>2</th><th>3</th></tr>";
$('#table').append(header);
for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
if (key.substring(0, 5) == "xyz") {
var value = JSON.parse(localStorage.getItem(key));
var xyzvalue = "<tr><td><input type=\"checkbox\" value=" + key + "></td><td><input type=\"text\" value=" + value[0] + "></td><td><input type=\"text\" value=" + value[1] + "</td><td><input type=\"text\" value=" + value[2] + "</td><td><input type=\"text\" value=" + value[3] + "</td></tr>";
$('#table').append(xyzvalue);
}
}
$('#table:input').prop("disabled", true);
}
The addValueToStorage is able to read data from the cells of a normal table, but since my table is editable I have used textboxes inside the table and the addValueToStorage is not able to read the data from the cells and also the table size is completely distorted and is overflowing the div enclosing it because of the textboxes.
Any help on extracting the data and setting the size of the table is greatly appreciated. Thanks in Advance
try changing:
for (i = 0; i < rowLength; i++) {
var value=[];
for (j = 0; j < 4; j++) {
value.push(table.rows[i].cells[j].firstChild.data);
}
var val=JSON.stringify(value);
var key = "xyz" + localStorage.length;
localStorage.setItem(key, val);
}
to
for (i = 0; i < rowLength; i++) {
var value=[];
for (j = 0; j < 4; j++) {
// getAttribute is probably what you're after here
value.push(table.rows[i].cells[j].firstChild.getAttribute('value'));
}
var val=JSON.stringify(value);
var key = "xyz" + localStorage.length;
localStorage.setItem(key, val);
}
I did my own feature using this:
function save(title, url)
{
for (var i = 1; i < localStorage.length; i++)
{
localStorage["saved-title_" + i + ""] = title;
localStorage["saved-url_" + i + ""] = url;
}
}
function listFavs()
{
for (var i = 1; i < localStorage.length; i++) {
console.log(localStorage["saved-fav-title_" + i + ""]);
}
}
save() happens when someone clicks on this:
onclick="save(\'' + title + '\', \'' + tab.url + '\');"> ' + title + '</a>';
However... it doesn't show the saved localStorages, how am I supposed to make it work?
Might it be because you are using the key 'saved-title_' + i to save the value and 'saved-fav-title_' + i to retrieve it?
The difference is the fav- part.
And your enumeration of the localStorage is bound to create errors as there is no guarantee that all items in it have a key that matches the pattern provided 'saved-fav-title_' + i - actually it is guaranteed to not be so as you are yourself inputting items with keys in the form of 'saved-url_'+ i.
So, if you want to properly enumerate the items with a key matching a pattern use
function listFavs(){
var key;
for (var i = 0, len = localStorage.length; i < len; i++){
key = localStorage.key(i);
if ((/^saved-fav-title_/).test(key)) {
console.log(localStorage.getItem(key);
}
}
}