Pass value from loop to javascript function - javascript

I have following code:
var storedNames = JSON.parse(localStorage.name);
var mytable = "<table> cellpadding=\"0\" cellspacing=\"0\"><tbody><tr>";
for (var i = 0; i < storedNames.length; i++) {
if (i % 2 == 1 && i != 1) {
mytable += "</tr><tr>";
}
mytable += "<td>" + storedNames[i].name +" "+ storedNames[i].email+"</td><td><img id='arrow' src='arrow.png' height='20' width='20' onclick='redirectToDetail();' ></td></tr>";
}
mytable += "</tbody></table>";
document.write(mytable);
here, in redirectToDetail function i want to i value . How can I pass this?
Any idea?
thank u in advance

try this
mytable += "<td>" + storedNames[i].name +" "+ storedNames[i].email+"</td><td><img id='arrow' src='arrow.png' height='20' width='20' onclick='redirectToDetail(\'"+ i +"\');' ></td></tr>";
and take that in redirectToDetail
function redirectToDetail(val){
alert(val);
}

Just add the value as a literal constant that is passed to the onclick event and you are home free. In addition, I would strongly encourage you to consider using an array and joining the strings as you will yield much better performance particularly in IE.
var storedNames = JSON.parse(localStorage.name);
var mytable = ['<table cellpadding="0" cellspacing="0"><tbody><tr>'];
for (var i = 0; i < storedNames.length; i++) {
if (i % 2 == 1 && i != 1) {
mytable.push("</tr><tr>");
}
mytable.push('<td>' + storedNames[i].name + ' ' + storedNames[i].email + '</td><td><img id="arrow" src="arrow.png" height="20" width="20" onclick="redirectToDetail(' + i + '"></td></tr>"');
}
mytable.push("</tbody></table>");
document.write(mytable.join());
Now you can declare you onclick function like so:
function redirectToDetail(value) {
//do stuff with the value
}

try this
onclick='redirectToDetail(\'"+i+"\')

I think this will do. check it.
mytable += "<td>" + storedNames[i].name +" "+ storedNames[i].email+"</td><td><img id='arrow' src='arrow.png' height='20' width='20' onclick='redirectToDetail(" + i + ");' ></td></tr>";

Related

Dynamic option list from an array

I have the following code which works perfectly, but can I make the drop menu dynamic using quantityAllowed as the maximum the drop menu goes to. at the moment I have added 10 options for every print, but what i would prefer is the drop menus only have the correct quantity in. I think the loop I need would go where the options begin using the value of the loop, but when i have tried, i just get an error, so I know I have done something wrong.
function arrayData() {
var index;
var text = "<ul>";
var htmlTable = '';
var calcTable = [];
calcTable = [
{ printName:"Name1", printPrice:8000000, quantityAllowed:6},
{ printName:"Name2", printPrice:12000000, quantityAllowed:5},
{ printName:"Name3", printPrice:20000000, quantityAllowed:4},
{ printName:"Name4", printPrice:2000000, quantityAllowed:3},
];//end of array
for (index = 0; index < calcTable.length; index++) {
var myclass = 'class="printwant"';
$("#tbNames tr:last").after("<tr>" +
"<td style='padding:0px 0px 0px 36px;'>" + calcTable[index].printName + "</td>" +
"<td class='printpoints'>" + calcTable[index].printPrice + "</td>" +
"<td>" + calcTable[index].quantityAllowed + "</td>" +
"<td><select " + myclass + "><option value=0>0</option><option value=1>1</option><option value=2>2</option><option value=3>3</option><option value=4>4</option><option value=5>5</option><option value=6>6</option><option value=7>7</option><option value=8>8</option><option value=9>9</option><option value=10>10</option></select></td><td></td> </tr>");
}//end of loop
$("#tbNames tr:last").after("<tr>" + "<td colspan = '5' height=40 > </tr>");
}
You can separate out your HTML generation code from the jQuery DOM assignment. This makes it a little easier to read and manipulate. When you come to your select/option area, drop it into a for... loop to generate the appropriate number of options.
function arrayData() {
var index;
var text = "<ul>";
var htmlTable = '';
var calcTable = [];
calcTable = [
{ printName:"Name1", printPrice:8000000, quantityAllowed:6},
{ printName:"Name2", printPrice:12000000, quantityAllowed:5},
{ printName:"Name3", printPrice:20000000, quantityAllowed:4},
{ printName:"Name4", printPrice:2000000, quantityAllowed:3},
];//end of array
for (index = 0; index < calcTable.length; index++) {
var myclass = 'class="printwant"';
var output = '';
output += "<tr>";
output += "<td style='padding:0px 0px 0px 36px;'>" + calcTable[index].printName + "</td>";
output += "<td class='printpoints'>" + calcTable[index].printPrice + "</td>";
output += "<td>" + calcTable[index].quantityAllowed + "</td>";
output += "<td><select " + myclass + ">";
for( var i=0, x=calcTable[index].quantityAllowed; i<x; i++ ){
output += '<option value="' + i + '">' + i + '</option>';
}
output += "</select></td><td></td> </tr>";
$("#tbNames tr:last").after(output);
}//end of loop
$("#tbNames tr:last").after("<tr>" + "<td colspan = '5' height=40 > </tr>");
}
arrayData();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tbNames">
<tr></tr>
<tr></tr>
</table>

JavaScript function doesn't execute everything

I have an array Orte that contains postcode and the name of the city.
Now I want to change the dropdown depending on the number entered in the input field.
The input field has an onchange function. The function is the one below.
The script works so far except the last line after the for loop. It never adds the last part and I don't know why.
Can someone help me please.
Thanks in advance for the anwsers!
Burzi
function updateOrt(eingabe){
document.getElementById("ort_platzhalter").innerHTML = '<select name="ort">'
for (var i = 1; i <= Orte.length; i++){
if(Orte[i].PLZ == eingabe){
document.getElementById("ort_platzhalter").innerHTML += '<option value="' + Orte[i].id + '">' + Orte[i].Ort + '</option>'
}
}
document.getElementById("ort_platzhalter").innerHTML += "</select>"
}
You should update the innerHTML in one shot. Build up the string first, then assign it. Also, arrays are zero-indexed, so I am guessing you want to start at 0, and end once it is the length of Orte (i = Orte.length).
function updateOrt(eingabe){
var str = '<select name="ort">'
for (var i = 0; i < Orte.length; i++){
if(Orte[i].PLZ == eingabe){
str += '<option value="' + Orte[i].id + '">' + Orte[i].Ort + '</option>'
}
}
str += "</select>"
// now assign the str to innerHTML
document.getElementById("ort_platzhalter").innerHTML = str;
}
your problem is in the array loop.
You are going from 1 to Orte.length, when it reaches Orte.length it throws an exception and the code after the loop does not execute.
you should do it this way:
function updateOrt(eingabe){
document.getElementById("ort_platzhalter").innerHTML = '<select name="ort">'
for (var i = 0; i < Orte.length; i++){
if(Orte[i].PLZ == eingabe){
document.getElementById("ort_platzhalter").innerHTML += '<option value="' + Orte[i].id + '">' + Orte[i].Ort + '</option>'
}
}
document.getElementById("ort_platzhalter").innerHTML += "</select>"
}
because arrays in javascript are 0 indexed and go up to length-1

Ajax Callback to append a select dropdown html to table?

I am trying to append some html using jQuery using below code. This whole thing i am just trying to select an option using ajax response data and building a select dropdown. But sOut variable scope not able to persist appended html inside callback function looping. Is there any work around to achieve what i am doing?
getVendor(aData[2], function (response) {
var obj = jQuery.parseJSON(response);
var sOut = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">';
var industries_select = '<tr><td>Industry:</td><td><select class="form-control m-bot15">';
getIndustries(function (response) {
var industries = jQuery.parseJSON(response);
for (var l = 0; l < industries.length; l++) {
if (industries[l].id == obj.industry) {
industries_select += '<option value="' + industries[l].id + '" selected="selected">' + industries[l].name + '</option>'
} else {
industries_select += '<option value="' + industries[l].id + '">' + industries[l].name + '</option>'
}
}
});
industries_select += '</select></td></tr>';
sOut += industries_select;
sOut += '</table>';
});
That's the expected behavior of async request. you should be doing something like this
getVendor(aData[2], function (response) {
var obj = jQuery.parseJSON(response);
var sOut = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">';
var industries_select = '<tr><td>Industry:</td><td><select class="form-control m-bot15">';
getIndustries(function (response) {
var industries = jQuery.parseJSON(response);
for (var l = 0; l < industries.length; l++) {
if (industries[l].id == obj.industry) {
industries_select += '<option value="' + industries[l].id + '" selected="selected">' + industries[l].name + '</option>'
} else {
industries_select += '<option value="' + industries[l].id + '">' + industries[l].name + '</option>'
}
}
industries_select += '</select></td></tr>';
sOut += industries_select;
sOut += '</table>';
});
});
Because, the callback of getIndustries will be called later point in time, and when the time you access industries_select outside the function, it's undefined.
If, for example, you're building the HTML dynamically then you may try appending the sOut variable to a Div tag inside your function scope, for example:
HTML:
<div id="dynamic"></div>
JQuery:
$("#dynamic").append(sOut);

JavaScript-How to make Html Table editable

I have a function of creating table from a .csv file using JavaScript. I want to make the last column of the table editable. Part of that function where table is being generated is
for (var i = 0; i < CSVLines.length; i++) {
OutputTableRows += "<tr>";
var CSVValues = CSVLines[i].split(",");
for (var j = 0; j < CSVValues.length; j++) {
OutputTableRows += "<td>" + "<p>" + CSVValues[j] + "<p>" + "</td>";
}
OutputTableRows += "</tr>";
}
I have tried
OutputTableRows += "<td>" + "<p contenteditable="true">" + CSVValues[j] + "<p>" + "</td>";
but it's not working
I think you should say in your inner loop:-
if(j == CSVValues.length-1){
tableRow = '<td><input type="text" value="VALUE"/></td>';
tableRow = tableRow.replace('VALUE',CSVValues[j]);
OutputTableRows += tableRow;
}
else{
OutputTableRows += "<td>" + "<p>" + CSVValues[j] + "<p>" + "</td>";
}
I'd suggest, at first glance:
OutputTableRows += "<td>" + "<p" + (j === (CSVValues.length - 1) ? " contentEditable" : "") + ">" + CSVValues[j] + "</p>" +"</td>";
The relevant part, of course, is:
"<p" + (j === (CSVValues.length - 1) ? " contentEditable" : "") + ">"
If j is equal to the length of CSVValues minus 1, then it's reasonable to assume that this must be the last iteration of that for loop, and therefore this is the row that should have the contentEditable attribute, otherwise it should not (and must be an earlier iteration of the loop).
Also, note the changed </p> (from your original <p>), which closes the already-open <p>, as opposed to creating a new, sibling, paragraph element.
References:
Conditional ('ternary') operator.
contentEditable attribute.

Alternate row colors in javascript

I'm making a table which have alternate row colors, for example the first row is red, the second is green, the third is red and so on.
Written this code so far and got stuck, don't know what to put in if statement.
var color = "red";
var outputString = "<table border=1 width=50%>";
outputString = outputString + "<tr><td>a</td><td>a^2</td><td>a^3</td></tr>";
for (var i = 1; i <= 5; i++ ) {
if (i%2 == 0) {
} else {
}
outputString += "<tr class=" + color + ">" + "<td>" + i + "</td>" + "<td>" + i * i + "</td>" + "<td>" + i * i * i + "</td>" + "</tr>";
}
outputString += "</table>";
document.write(outputString);
Here is the pure css version,
table tr:nth-child(odd) td{
}
table tr:nth-child(even) td{
}
And here is the jQuery solution for the same,
$(function(){
$("table tr:even").addClass("evenClassName");
$("table tr:odd").addClass("oddClassName");
});
Here is the pure JavaScript solution,
function altrows(firstcolor,secondcolor)
{
var tableElements = document.getElementsByTagName("table") ;
for(var j = 0; j < tableElements.length; j++)
{
var table = tableElements[j] ;
var rows = table.getElementsByTagName("tr") ;
for(var i = 0; i <= rows.length; i++)
{
if(i%2==0){
rows[i].style.backgroundColor = firstcolor ;
}
else{
rows[i].style.backgroundColor = secondcolor ;
}
}
}
}
Use this(JQUERY WAY):-
$(document).ready(function()
{
$("table#tblid tr:even").css("background-color", "color code");
$("table#tblid tr:odd").css("background-color", "color code");
});
Here is the JavaScript way of doing it:-
var tblrows = document.getElementsByTagName('tr');
for(i=0;i<tblrows.length;i++){
if(i%2==0) tblrows[i].style.backgroundColor = '#f22000';
else tblrows[i].style.backgroundColor = '#a02141';
}
JS FIDDLE
use this, it will apply for all tables too
var tr = document.getElementsByTagName('tr');
for(i=0;i<tr.length;i++){
if(i%2==0) tr[i].style.backgroundColor = 'red';
}
DEMO
if you want to highlight the trs that have at least a td element inside use this :
var tr = document.getElementsByTagName('tr');
for(i=0;i<tr.length;i++){
if(i%2==0 && tr[i].getElementsByTagName('td').length) tr[i].style.backgroundColor = 'red';
}
Here is an alternative pure JavaScript + CSS solution.
// get all even rows
var evenRows = document.querySelectorAll('tr:nth-child(even)');
// get all odd rows
var oddRows = document.querySelectorAll('tr:nth-child(odd)');
// set even rows background color
evenRows.forEach((evenRow) => { evenRow.style.backgroundColor = 'myEvenRowColor'; });
// set odd rows background color
oddRows.forEach((oddRow) => { oddRow.style.backgroundColor = 'myOddRowColor'; });
This takes advantage of JavaScript's querySelectorAll and forEach functions and CSS selectors.
The above code can also be written in two lines:
document.querySelectorAll('tr:nth-child(even)').forEach((evenRow) => { evenRow.style.backgroundColor = 'myEvenRowColor'; });
document.querySelectorAll('tr:nth-child(odd)').forEach((oddRow) => { oddRow.style.backgroundColor = 'myOddRowColor'; });
Using just your code as a basis you'll want to do this in the if statement:
var color_even = "red";
var color_odd = "green";
var outputString = "<table border=1 width=50%>";
outputString = outputString + "<tr><td>a</td><td>a^2</td><td>a^3</td></tr>";
for (var i = 1; i <= 5; i++ ) {
if (i%2 == 0) {
color_used = color_even;
} else {
color_used = color_odd;
}
outputString += "<tr class=\"" + color_used + "\">" + "<td>" + i + "</td>" + "<td>" + i * i + "</td>" + "<td>" + i * i * i + "</td>" + "</tr>";
}
outputString += "</table>";
document.write(outputString);

Categories

Resources