I have a simple question. I want to make an if statement in this code (if(i=2){str += 'test';}):
var data = response.DATA;
var str = '<ul>';
for (var I = 0; I < data.length; I++) {
str += '<li>' + data[I][1] + '</li>';
if(I=2){str += 'test';}
}
str += '</ul>';
$('#output').html(str);
}
When I do, it's placing the word 'test' not only at row 2, but on every row.
Use == or === to compare two values :
if (I===2) {str += 'test';}
The result of I=2, which changes the value of I, is 2, which evaluates as true in an if.
You have a typo in your script:
if (I=2) ...
means that I is always 2 because you're assigning 2 to it.
Related
I have a JSON encoded AJAX object array and I need to iterate every other one. I'm new to jQuery and JS and are unsure how to do this. I need the numbers to be the option value and the string name as the object name.
The AJAX object (note although in this example the numerals are in order they might not be because the integers are an auto_id from a database and numbers might be skipped or out of order:
{"data":["1","chicken","2","beef","3","fish","4","pork","5","turkey","6","lamb","7","vennison","8","duck"],"error":false}
I tried the following code below which doesn't work. I tried to do a search for this answer but couldn't find it. TIA. Currently, newOption is returning "undefined".
$.each(data.data, function(i,s){
var count=s[i];
var newOption = s[i+1];
output += '<option value="' + count + '">' + newOption + '</option>';
i++;
});
Use a for loop, but increment the counter by 2 each loop:
var data = {"data":["1","chicken","2","beef","3","fish","4","pork","5","turkey","6","lamb","7","vennison","8","duck"],"error":false}
var output = '';
for(i = 0; i < data.data.length; i+=2) {
output += '<option value="' + data.data[i] + '">' + data.data[i+1] + '</option>';
}
https://jsfiddle.net/go98npym/
When Iterating over a Array using jQuery.each the first param is index and the second one is value in the index itself.
Instead of using jQuery use plain javascript.
try the following:
var d = data.data;
var output = "";
for (var i = 0 ; i< d.length; i=i+2) {
var count = d[i];
var newOption = d[i+1];
output += "<option value='"+count+"'>"+newOption+"</option>";
}
Can you use an if statement with modulus? And then initialize your count outside the loop.
var count = 0;
$.each(data.data, function(i,element){
if (i % 2 == 0) {
count++;
output += '<option value="' + count + '">' + element + '</option>';
}
i++;
});
I have a problem to use the operator += in an object.
Because i have to change the variable dynamically i use an object as variable.
But if i use the += operator the first element in the output always gets undefined. I think thats because the object is initialized empty.
What is the best solution to prevent to output that element ?
Here goes my example code:
var dynamicVariable = {};
var group = "apples";
for(var i = 1; i<5; i++)
{
dynamicVariable[group] += " Apple" + i + "<br>";
}
document.getElementById("fruits").innerHTML = dynamicVariable[group];
jsFiddle
This is happening because dynamicVariable[group] has the value undefined before you start appending to it. undefined + " Apple1" is "undefined Apple1".
You need to initialize it to an empty string first:
dynamicVariable[group] = "";
for(var i = 1; i<5; i++) {
dynamicVariable[group] += " Apple" + i + "<br>";
}
So let me just start out by saying that I don't have much experience with Javascript. If someone could give me a basic explanation, that would be great.
Anyways, I want to take a two dimensional matrix and print it on the screen. This is my code so far:
function matrixToString(arr) {
returnString = "";
for (var i = 0; i < arr.length; i++){
for (var j = 0; j < arr[i].length; j++){
returnString += Math.round(arr[i][j]*10000)/10000 + ' ';
}
returnString += "\n";
}
return returnString
}
So when I call alert(matrixToString(n)), it works as expected. However, when I use document.write(matrixToString(n)), it basically puts everything on one line and prints that line. The same applies if I put the string into a div and append the div.
I guess my question is basically how do I put multi-line outputs to HTML in javascript.
Is your multiline requirement only for presentation purpose? If so, then you just need to add '' to the end of each line. '\n' does not work when rendering HTML. Instead just replace:
returnString += "\n";
with
returnString += "<br/>";
in you code just replce \n with "br"
like this
function matrixToString(arr) {
returnString = "";
for (var i = 0; i < arr.length; i++){
for (var j = 0; j < arr[i].length; j++){
returnString += Math.round(arr[i][j]*10000)/10000 + ' ';
}
returnString += "<br>";
}
return returnString
}
this works for my case
document.write is outdated and hence try directly manipulate DOM.
For example:
<div id="demo"></div>
JS:
document.getElementById('demo').innerHTML = matrixToString(n);
Also with reference to this answer,
It depends on what you're doing with the text, but my guess is you're
rendering it as Html. In that case, you should be using a <br /> tag
instead of a \n.
so use returnString += "<br />"; to solve your problem.
I'm working on project in which I have to create a search engine through jQuery. Everything has been going great until I started looping through the array.
I don't know whether I'm doing it wrong, but for some reason, when I use a conditional it does not output the statement I want it to say. If I change the conditional to say whether there's something in the array output this, it does. But if the array is empty it does absolutely nothing. Why is that?
for(var i = 0, j = response.length; i < j; i++){
var searchItemRes = response[i];
if(response.length === 0){
$('' + '<ul>' +
'<li><span>Nothing found, try again</span></li>' +
'</ul>'
).appendTo(searchResults);
}
$('' + '<ul>' +
'<li><img src="" /><span> '+searchItemRes.title+'</span></li>' +
'</ul>'
).appendTo(searchResults);
}
Consider this:
// declare local variables
var str, i, item;
// build the HTML source code string
if ( response.length === 0 ) {
str = '<ul><li><span>Nothing found. Please, try again.</span></li></ul>';
} else {
str = '<ul>';
for ( i = 0; i < response.length; i += 1 ) {
item = response[i];
str += '<li><img src=""><span> ' + item.title + '</span></li>';
}
str += '</ul>';
}
// append the string to the DOM
$( searchResults ).append( str );
First off, declare the local variables at the top of the function. As you can see, my code uses 3 local variables.
Next, I doubt that you want to create one UL (list-holder) for each result. It makes more sense to have one UL element which contains all the results (which is what I've implemented in the above code).
Also, I recommend manipulating the DOM only once at the end - the live-DOM should be touched as few times as possible. Therefore, the above code builds the HTML source code string "off-DOM", and only in the end appends (the whole thing) to the DOM.
for (var i = 0, j = response.length; i < j; i++){
var searchItemRes = response[i];
if (response.length === 0) {
$('<ul><li><span>Nothing found, try again</span></li></ul>').appendTo(searchResults);
}
...
}
That condition will never be executed. If i = 0 and j = response.length and it's iterating i < j then it won't iterate at all if response.length == 0 because 0 < 0 will just break out of the loop.
How can code that triggers on response.length == 0 ever execute inside a loop that iterates response.length times?
Perhaps you meant:
if (response.length === 0) {
$('<ul><li><span>Nothing found; try again</span></li></ul>').appendTo(searchResults);
}
else {
for (var i = 0, j = response.length; i < j; i++) {
var searchItemRes = response[i];
$('<ul>' +
'<li><img src="" /><span>' + searchItemRes.title + '</span></li>' +
'</ul>'
).appendTo(searchResults);
}
}
I've tried everything I can find via google and nothing has worked correctly. Output is just a single row with all the contents of the array listed. What I need is a way to write the contents of an array but after 3 cells, automatically start a new line. I'll post the code I've made below as well as the question. (yes this is from an assignment. :( )
//***(8) place the words in the string "tx_val" in a table with a one pixel border,
//*** with a gray backgound. Use only three cells per row. Empty cells should contain
//*** the word "null". Show the table in the span block with id="ans8"
var count = i % 3;
var nrow = "";
var out = "<table border='1' bgcolor='gray'><tr>"
for (var i=0; i<txArr.length; i++)
{
out += ("<td>" + txArr[i] + "</td>");
count++;
if (count % 3 == 0)
{
nrow += "</tr><tr>";
}
}
document.getElementById('ans8').innerHTML = out + nrow;
you need to print the tr's inside the table (annd add a </table>!):
var count = i % 3; // btw. what's this??
var nrow = "";
var out = "<table border='1' bgcolor='gray'><tr>"
for (var i=0; i<txArr.length; i++)
{
out += "<td>" + txArr[i] + "</td>";
count++;
if (count % 3 == 0)
out += "</tr><tr>";
}
out += "</table>";
document.getElementById('ans8').innerHTML = out;
Rather than try to write out the html, try manipulating the dom. It seems much more straightforward to me. Take a look at the following:
var row = table.insertRow();
msdn
mdc
var cell = row.insertCell();
msdn
mdc
var cellContent = document.createTextNode(txArr[i]);
msdn
mdc
cell.appendChild(cellContent);
msdn
mdc
For deciding when to start a new row, just use the modulus operator (%
msdn
mdc
) against i:
if (i % 3 == 0)
{
row = table.insertRow()
}
You'd end up with something like this:
var container = document.getElementById("ans8");
var t = container.appendChild(document.createElement("table"));
var row;
txArr.forEach(function (item, i)
{
if (i % 3 == 0)
{
row = t.insertRow()
}
row.insertCell().appendChild(document.createTextNode(item));
});
I'll leave a little for you to figure out - border, background color, getting the word "null" in there. It is your homework after all. :-)
Also, for older browsers you'll need to add Array.forEach in yourself.
I prefer using an array over concatination
var html = [];
html.push("<table><tr>");
var i = 0;
for (var k in txArr)
{
if(i>=3){
i=0;
html.push("</tr><tr>");
}
html.push("<td>" + txArr[k] + "</td>");
i++;
}
html.push("</tr></table>");
document.getElementById('ans8').innerHTML = html.join('');
// wrapped in function
function arrayToTable(a,cols){
var html = [];
html.push("<table><tr>");
var i = 0;
for (var k in a)
{
if(i>=cols){
i=0;
html.push("</tr><tr>");
}
html.push("<td>" + a[k] + "</td>");
i++;
}
html.push("</tr></table>");
return html.join('')
}
document.getElementById('ans8').innerHTML = arrayToTable(txArr, 3);
It might be a tad easier to accomplish with something like
buffer = "<table>";
for(var r = 0; r < 10; r++){
buffer += "<tr>";
for(var c = 0; c < 3 ; c++){
buffer += "<td>Cell: " + r + ":" + c + "</td>";
}
buffer += "</tr>";
}
buffer += "</table>";
document.getElementById("ans8").innerHTML = buffer;
That would create a table 30 rows long by 3 columns for each row.
you might be assigning values to "count" too early as you don't know what i is yet. and you are not spitting out the value of nrow anywhere... change it to out.
var count;
var nrow = "";
var out = "<table border='1' bgcolor='gray'><tr>"
for (var i=0; i<txArr.length; i++)
{
out += ("<td>" + txArr[i] + "</td>");
count++;
if (count % 3 == 0)
{
out += "</tr><tr>";
}
}
document.getElementById('ans8').innerHTML = out + nrow;
Basically I would split it up into 3 functions, for readability and maintenance. These functions would consist of creating a cell, a row, and a table. This definitely simplifies reading the code. As I have not tested it, below is an example of what I would do.
function createTableCell(value) {
return value == null? "<td>NULL</td>":"<td>" + value + "</td>";
}
function createTableRow(array) {
var returnValue = "";
for (var i = 0; i < array.length; i++) {
returnValue = returnValue + createTableCell(array[i]);
}
return "<tr>" + returnValue + "</tr>";
}
function arrayToTable(array, newRowAfterNArrayElements) {
var returnValue = "<table>";
for (var i = 0; i < array.length; i = i + newRowAfterNArrayElements) {
returnValue = returnValue + createTableRow(array.split(i, (i + newRowAfterNArrayElements) - 1));
}
return returnValue + "</table>";
}
document.getElementById("ans8").innerHTML = arrayToTable(txArr, 3);
In addition this makes your code much more dynamic and reusable. Suppose you have an array you want to split at every 4 element. Instead of hardcoding that you can simply pass a different argument.
Here's a live example of doing this with DOMBuilder, and of using the same code to generate DOM Elements and an HTML String.
http://jsfiddle.net/insin/hntxW/
Code:
var dom = DOMBuilder.elementFunctions;
function arrayToTable(a, cols) {
var rows = [];
for (var i = 0, l = a.length; i < l; i += cols) {
rows.push(a.slice(i, i + cols));
}
return dom.TABLE({border: 1, bgcolor: 'gray'},
dom.TBODY(
dom.TR.map(rows, function(cells) {
return dom.TD.map(cells);
})
)
);
}
var data = [1, 2, null, 3, null, 4, null, 5, 6];
document.body.appendChild(arrayToTable(data, 3));
document.body.appendChild(
dom.TEXTAREA({cols: 60, rows: 6},
DOMBuilder.withMode("HTML", function() {
return ""+arrayToTable(data, 3);
})
)
);
Yes, you can build from scratch...but there's a faster way. Throw a grid at it. The grid will take data in a string, array, json output, etc and turn it into a proper HTML outputted table and will allow you to extend it with sorting, paging, filtering, etc.
My personal favorite is DataTables, but there are numerous others out there.
Once you get proficient, setting one of these up literally takes 5 minutes. Save your brain power to cure world hunger, code the next facebook, etc....