function Controles(contro, nomtab, numtab, action, nomcla, tipdat, lista, datos) {
$(document).on('click', '.'+contro+' #IZQTOD', function(event) {
$.getJSON(action+'&rows='+rows+'&page=1', function(datos) {
var nuevafila;
$.each(datos+tipdat, function(index, data) {
nuevafila = nuevafila + "<tr class='Fila-Grid-"+nomcla+"' id='" + numtab + (index + 1) + "'>";
nuevafila = nuevafila + "<td class='Columna1'>" + (index + 1) + "</td>";
var list = lista.split("-");
for (var j = 1; j < list.length; j++) {
nuevafila = nuevafila + "<td class='Borde-'>" + data+list[j] + "</td>";
}
nuevafila = nuevafila + "</tr>";
});
$('#'+nomtab+' tr:eq(1)').after(nuevafila);
});
});
}
I want to run this piece of code as a function of javascript in order to reuse code.
The part that does not work for me is the part of each:
$. each (+ tipdat data, function (index, data) {
Where "datos" is an object with variables (set and get) (codcli, name, apepat)
I mean to call codcli I do:
$. each (datos.codcli, function (index, data) {
}
But this way is static. I want to do through dynamic parameters.
So the question is how to pass parameters to successfully achieve? Or is that you can not do? There will always be static?
in the code above what I want to do is, but obviously does not work:
tipdat=".codcli"
$. each (datos+tipdat, function (index, data) {
}
I think you're looking for bracket notation.
var tipdat = "codcli";
$.each(datos[tipdat], function (index, data) {
//...
});
Is the same as:
$.each(datos.codcli, ...
If your string has multiple properties, I would do something like this:
var tipdat = "codcli.cod";
var objToIterate = datos;
var parts = tipdate.split('.');
for(var i = 0; i< parts.length; i++) {
objToIterate = objToIterate[parts[i]];
}
$.each(objToIterate, function (index, data) {
//...
});
Related
I think I am getting a logic problem using jQuery to fetch record from a service API with AJAX and using following piece of code.
There is no error but this code is repeating records in HTML table (Drafts) -
like twice.
success: function (data) {
if (data) {
console.log(data);
var textDraft = "";
for (var i = 0; i < data.TableDrafts.length; i++) {
textDraft += "<tr><td>" + data.TableDrafts[i].nMBM + "</td><td>" + data.TableDrafts[i].nMTM + "</td><td>" + data.TableDrafts[i].sType + "</td></tr>";
$("#Drafts").append(textDraft);
}
}
}
Here you go with a solution
success: function (data) {
if (data) {
console.log(data);
var textDraft = "";
for (var i = 0; i < data.TableDrafts.length; i++) {
$("#Drafts").append(`<tr>
<td>${data.TableDrafts[i].nMBM}</td>
<td>${data.TableDrafts[i].nMTM}</td>
<td>${data.TableDrafts[i].sType}</td>
</tr>`);
}
}
}
Mistake was, you are adding the new tr in the variable as well as appending the variable content.
Or else you can do
success: function (data) {
if (data) {
console.log(data);
var textDraft = "";
for (var i = 0; i < data.TableDrafts.length; i++) {
textDraft = "<tr><td>" + data.TableDrafts[i].nMBM + "</td><td>" + data.TableDrafts[i].nMTM + "</td><td>" + data.TableDrafts[i].sType + "</td></tr>";
$("#Drafts").append(textDraft);
}
}
}
Hope this will help you.
I have multiple items in my JSON list. I want to loop through it and display it on my page. I can't seem to get to the next object though.
{
"room":[
{"campusName":"A",
"buildingCode":"B",
"roomNumber":"208",
"times":["7-8", "9-10"]
}],
"room2":[
{"campusName":"C",
"buildingCode":"D",
"roomNumber":"208",
"times":["7-8", "9-10"
]}
]}
$(document).ready(function(){
$.getJSON("data.json", function(data){
$.each(data.room, function(){
for(var i = 0; i < data.length; i++){
$("ul").append("<li>campus: "+this['campusName']+"</li><li>building: "+this['buildingCode']+"</li><li>times: "+this.times+"</li>");
}
});
});
});
Try this
var list = '';
$.each(data, function (i, root) {
$.each(root, function (i, el) {
list += "<li>campus: " + this.campusName + "</li><li>building: " + this.buildingCode + "</li><li>times: " + this.times.join(' ') + "</li>";
});
});
$('ul').html(list);
Example
If root's has only one element in array
var list = '';
$.each(data, function (i, root) {
list += "<li>campus: " + root[0].campusName + "</li><li>building: " + root[0].buildingCode + "</li><li>times: " + root[0].times.join(' ') + "</li>";
});
$('ul').html(list);
Example
$.each(data, ..) --> Each element will be:
"room":[
{"campusName":"A",
"buildingCode":"B",
"roomNumber":"208",
"times":["7-8", "9-10"]
}]
Then, this[0] will provide the object you need to construct your li:
$.each(data, function(){
$("ul").append("<li>campus: "+this[0]['campusName']+"</li><li>building: "+this[0]['buildingCode']+"</li><li>times: "+this[0].times+"</li>");
});
Fiddle
I am using my function in onclick nav tabs event (when click on any tab this below function activates). I just want that no same name can twice be inserted into the dropdownlist. Below function is working just perfectly. I just need a check maybe like name.text != arr[i] something like that to prevent it to insert the same name twice in the list. Any help would be appreciated.
js:
<script>
$(".nav-tabs li").click
(
function()
{
var getnumber = document.getElementById("permanentno").value;
var getData = 'methodname=getList&no='+getnumber;
$.ajax
({
type: 'GET',
url: 'Dropdown List/List.php',
data: getData,
success: function(resp)
{
alert(resp); // names for example: mile,stone,
var arr = resp.split(",");
var list = $(".dropdownlist");
var html = "";
for(var i = 0; i < arr.length; i++)
{
var name = arr[i];
if(name.length != 0)
{
html += "<option value='" + name + "'>";
html += name;
html += "</option>";
}
}
$(".dropdownlist").append(html);
}
});
}
);
</script>
You could keep track of the names with another array and IndexOf. Note that for IE<9 support you'll need a shiv to use it.
var names = [];
for(var i = 0; i < arr.length; i++)
{
var name = arr[i];
if(name.length != 0 && names.indexOf(name) == -1)
{
html += "<option value='" + name + "'>";
html += name;
html += "</option>";
names.push(name);
}
}
You can append options to the dropdownlist on the loop, and check repeated names using jQuery like:
var list = $(".dropdownlist");
for (var i = 0; i < arr.length; i++) {
var name = arr[i];
if (name.length != 0 && !list.find("option[value='" + name + "']").length) {
var html = "<option value='" + name + "'>";
html += name;
html += "</option>";
list.append(html);
}
}
Below is the script:
$(document).ready(function () {
$.getJSON('table.json', function (data) {
$('#mytable').empty();
var html = '';
html += '<tr class="tableheader"><th>Name</th><th>Code</th><th>Value</th><th>Bid</th><th>Offer</th></tr>';
for (var i = 0, size = data.length; i < size; i++) {
html += '<tr class="tablecontent"><td>' + data[i].name + '</td><td>' + data[i].code + '</td><td>' + data[i].value + '</td><td>' + data[i].bid + '</td><td>' + data[i].offer + '</td></tr>';
}
$('#mytable').append(html);
tablerows('mytable');
setTimeout(poll, 5000);
});
});
var poll = function () {
alert("poll");
$.getJSON('dummy.json', function (data) {
setTimeout(poll, 5000);
});
}
I want to update my data. The poll function is getting called after every 5 seconds which I checked through the alert. But data is not getting updated. Please tell me what I am doing wrong.
getJSON is a GET request so it will be cached. Set the proper no cache headers on the server.
Also look at your code, you are never processing the data
var poll = function () {
alert("poll");
$.getJSON('dummy.json', function (data) {
setTimeout(poll, 5000); //<--where is the processing you do nothing with the response???
});
}
$(document).ready(function() {
// make the initial JSON request
$.getJSON('table.json', init)
});
function poll() {
// make the subsequent JSON requests
$.getJSON('dummy.json', update);
}
function init(data) {
$('#mytable').empty();
var html = '';
html += '<tr class="tableheader"><th>Name</th><th>Code</th><th>Value</th><th>Bid</th><th>Offer</th></tr>';
for (var i = 0, size = data.length; i < size; i++) {
html += '<tr class="tablecontent"><td>' + data[i].name + '</td><td>' + data[i].code + '</td><td>' + data[i].value + '</td><td>' + data[i].bid + '</td><td>' + data[i].offer + '</td></tr>';
}
$('#mytable').append(html);
tablerows('mytable');
setTimeout(poll, 5000);
}
function update(data) {
var rows = $("#mytable tr.tablecontent").toArray();
for (var i = 0, size = data.length; i < size; i++) {
if (rows[i])
rows[i].cells[3].firstChild.data = data[i].bid;
}
setTimeout(poll, 5000);
}
Here's the update function with more jQuery:
function update(data) {
$("#mytable tr.tablecontent > td:nth-child(4)")
.slice(0, data.length)
.text(function(i) {
return data[i].bid;
});
setTimeout(poll, 5000);
}
I'm trying to populate an array in JavaScript using an anonymous function in the jQuery getJSON() function as follows.
$(document).ready(function() {
function Link(url, title) {
this.url = url;
this.title = title;
}
var links = [];
$.getJSON("http://reddit.com/r/programming/.json?jsonp=?", function(data) {
$.each(data.data.children, function(i, item) {
var title = item.data.title;
var url = item.data.url;
links.push(new Link(url, title));
})
});
for(var i=0; i< links.length; i++) {
var output = "<a href='" + k + "'>" + links[k] + "</a>";
$('<p>' + link + '</p>').appendTo('#content');
}
});
But, when I hit the for loop, the links array shows up empty. What's going on here?
Try that :
$(document).ready(function() {
function Link(url, title) {
this.url = url;
this.title = title;
}
$.getJSON("http://reddit.com/r/programming/.json?jsonp=?", function(data) {
var links = [];
$.each(data.data.children, function(i, item) {
var title = item.data.title;
var url = item.data.url;
links.push(new Link(url, title));
})
for(var i=0; i< links.length; i++) {
var output = "<a href='" + k + "'>" + links[k] + "</a>";
$('<p>' + link + '</p>').appendTo('#content');
}
});
});
Your loop was probably executed before your callback ;)
That's because $.getJSON is an asynchronous method. The code execution continues even after $.getJSON and reaches the for loop, by which time, your async request hasn't completed yet. You should move the loop within $.getJSON.
This jsFiddle http://jsfiddle.net/cArYg/2/ shows the iteration occuring before the getJson callback