add onclick event to dynamically generated table - javascript

I've been working on a functionality that involves the creation of a HTML table using jquery that will display a list of accounts dynamically on page load, that's something I achieved without problems.
However, I've also asked to add an "onclick" event to each row that will redirect me to another web page, but that will depend on a parameter that I need to pass. Here's my code:
$(document).ready(function() {
var x = ['Visa-1234', 'Amex-9182', 'Visa-8162', 'Visa-9554'];
var message = 'No accounts found';
if (x.length > 0) {
message = 'Select an account to display the rewards information: ';
}
$('#message').text(message);
var tableContentHtml = '<table class="table-fill"><thead><tr><th class="text-left">Account</th></tr></thead><tbody class="table-hover">';
for (var i = 0; i < x.length; i++) {
tableContentHtml += '<tr><td class="text-left" onclick="goAnotherWebPage()">' + x[i] + '</td></tr>';
}
tableContentHtml += '</tbody></table>';
$(tableContentHtml).appendTo('#container');
});
function goAnotherWebPage(account) {
//do some logic here
}
The method "goAnotherWebPage" should receive the same account ID that is being displayed, I have no problem with that, the problem comes when I pass the x[i] as parameter on the table creation:
onclick="goAnotherWebPage(x[i])"
That is not working, it says that the account is not defined.
Can somebody give me a hint or provide help in order to achieve this? Thanks in advance!

Try this out
for (var i = 0; i < x.length; i++) {
tableContentHtml += '<tr><td class="text-left" onclick="goAnotherWebPage(\'' + x[i] + '\')">' + x[i] + '</td></tr>';
}
$(document).ready(function() {
var x = ['Visa-1234', 'Amex-9182', 'Visa-8162', 'Visa-9554'];
var message = 'No accounts found';
if (x.length > 0) {
message = 'Select an account to display the rewards information: ';
}
$('#message').text(message);
var tableContentHtml = '<table class="table-fill"><thead><tr><th class="text-left">Account</th></tr></thead><tbody class="table-hover">';
for (var i = 0; i < x.length; i++) {
tableContentHtml += '<tr><td class="text-left" onclick="goAnotherWebPage(\'' + x[i] + '\')">' + x[i] + '</td></tr>';
}
tableContentHtml += '</tbody></table>';
$(tableContentHtml).appendTo('#container');
goAnotherWebPage = function(account) {
console.log(account);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="message"></div>
<div id="container"></div>
Hope this will help you.

I try to understand what do you need and i create a simple demo for you
$(document).ready(function() {
var x = ['Visa-1234', 'Amex-9182', 'Visa-8162', 'Visa-9554'];
var message = 'No accounts found';
if (x.length > 0) {
message = 'Select an account to display the rewards information: ';
}
$('#message').text(message);
var tableContentHtml = '<table class="table-fill"><thead><tr><th class="text-left">Account</th></tr></thead><tbody class="table-hover">';
for (var i = 0; i < x.length; i++) {
tableContentHtml += '<tr><td class="text-left redirect">' + x[i] + '</td></tr>';
}
tableContentHtml += '</tbody></table>';
$(tableContentHtml).appendTo('#container');
});
$('body').on('click', '.redirect', function (e) {
value = $(this).html();
console.log(value);
// do your logic here
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="message"></div>
<div id="container"></div>

Related

Loop of html using javascript

i am new on using of JavaScript on looping of html. I have this code below that i am working at. In this problem of mine i have 2 loop the main and the card-body loop. As you can see in the code First I need to loop the main to create a card and then at the body i need also to loop it because of the data content. I have also working code below but as you can see at the card-body its not looping anymore but static data that I inputted.
Problem
for (var i = 0; i < dataLength; i++) {
var docsLength = data.data[i].resultData;
var title = data.data[i].resultData[i].Type.Description;
var card = '<div class="card"> <div class="card-header bg-success"><h3 class="card-title">' + title + ' </h3 ></div> <div class="card-body">'; for (var a = 0; a < 2; a++) { "a" } ' </div>' +
'</div >';
$("#card_documents > .card-body").append(card);
}
Working
for (var i = 0; i < dataLength; i++) {
var docsLength = data.data[i].resultData;
var title = data.data[i].resultData[i].Type.Description;
var card = '<div class="card"> <div class="card-header bg-success"><h3 class="card-title">' + title + ' </h3 ></div> <div class="card-body">' +
"asdasdasdasd" +
'</div > ' +
'</div >';
$("#card_documents > .card-body").append(card);
}
Is my syntax wrong?. Please help. Thanks
You can replace for (var a = 0; a < 2; a++) { "a" } with "a".repeat(2).
More info about repeat() here
Yes, your syntax is wrong. Specifically the way you're trying to use the for loop.
I would suggest building up the string in a variable.
Here is a stripped down version of how you might achieve that.
var card = '<div class="card">';
for (var a = 0; a < 2; a++) {
card += "a";
}
card += '</div>';
$("#card_documents > .card-body").append(card);

Modifying <img src style="visibility"> through JavaScript

I'm building a memory game in HTML & JS where you guess 2 different images and try to pick 2 same ones.
I'm stuck with putting an onclick function to a hidden image.
Here is my code so ill try to explain better...
var table = '';
for(var i = 0; i < 4; i++){
table += '<tr>';
for(var j = 0; j < 3; j++){
table += '<td align="center"><img src="./pics/image_part_00' + Math.floor((Math.random() * 6) + 1) + '.jpg";" width="100px"" onclick="clicked(this);" style="visibility: hidden;"></td>';
}
table += '</tr>';
}
document.getElementById('theGame').innerHTML = '<table border=1 cellpadding="10" class="tabela1">' + table + '</table>'
Now what im trying to do is to overwrite that visibility: hidden; so the image is visible when clicked....
And here is the function
function clicked(element){
element.style.visibility = "visible";
}
but it doesn't work because with that element.style.visibility im changing the visibility of a table cell.
Anyone got a solution? I'm probably missing something and can't figure it...
NOTE: It's a school assignment so it has to be in a table.
Here is a some fixed javascript. when you catch onclick event, it won't work on hidden elements. So I move event listener onto td:
var table = '';
for(var i = 0; i < 4; i++){
table += '<tr>';
for(var j = 0; j < 3; j++){
table += '<td align="center" onclick="click_it(this)">
<img src="./pics/image_part_00' + Math.floor((Math.random() * 6) + 1) + '.jpg"
width="100px" style="visibility: hidden"></td>';
}
table += '</tr>';
}
document.getElementById('theGame').innerHTML = '<table border=1 cellpadding="10" class="tabela1">' + table + '</table>';
function click_it(cell){
var image = cell.children[0];
image.style.visibility = 'visible';
}
You can search for the img child of the table cell
var child = element.childNodes;
The var child will return an array of elements, then you just need to access to the position that the is, and change the visibility attribute:
child[1].style.visibility = "visible";
You can try below,
just played a trick to match element id dynamically
to make it visible.
Added on click to td instead of image.
added id to image.
here is the code
<div id="theGame">
var table = '';
for (var i = 0; i < 4; i++) {
table += '<tr>';
for (var j = 0; j < 3; j++) {
table += '<td align="center" onclick="clicked(' + j + ')"> <img id=img_' + j + ' src="./pics/image_part_00' + Math.floor((Math.random() * 6) + 1) + '.jpg;" width="100px" style="visibility: hidden;"> </td>';
}
table += '</tr>';
}
document.getElementById('theGame').innerHTML = '<table border=1 cellpadding="10" class="tabela1">' + table + '</table>'
function clicked(element) {
document.getElementById('img_' + element).style.visibility = "visible";
}

i want to create new table dynamically and removed it by same button using jquery?

I want to show updated rows no every time. I have this code .want to remove and generate again as this same
var table = $('#table').children();
for (var j = i; j < result.length; j++) {
table.append("<tr><td>" + (j + 1) + "</td><td><b>" + result[j].VoterName + "</b></td><td><b>" + result[j].VoterContact + "</b></td><td><button>X</button></td></tr>");
i++;
}
function createOrDeleteTable(){
console.log("wadawdawd");
if($("#btn").attr("created") === "false") {
$("#btn").attr("created","true");
var tabledata = "<table>"
+ "<tr>"
+"<th> hey </th>"
+"<th> hello </th>"
+ "</tr>"
+ "</table>";
console.log(tabledata);
$("#appendHere").html(tabledata);
} else {
$("#btn").attr("created","false");
$("#appendHere").html("");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="createOrDeleteTable();" created="false" id="btn"> create table </button>
<div id="appendHere"> </div>

create table with values using js

I want to create table using javascript and fill it with data. So I decided to use prompt method and loop while.
But when I try to load page I always get two error message in google chrome developer tools
Here is the code
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
function onStart() {
var list = new Array();
var headers = new Array("Имя","Отчество","Фамилия","Дата рождения");
var i = -1;
while(true) {
var a = prompt("Имя","noname");
var b = prompt("Отчество","nomiddlename");
var c = prompt("Фамилия","nosurname");
var d = prompt("Дата рождения!",0);
if (confirm("Уверены что хотите добавить студента?")) {
i++;
list[i] = a + "-" + b + "-" + c + "-" + d;
}else{ break; };
}
tab = "<table>";
for(j = 0; j<headers.length;j++) {
tab += "<th>" + headers[j] + "</th>";
for(var j = 0; j < list.length; j++) {
var params = list[i].split('-');
tab += "<tr>";
for(k = 0; k < params.length;k++) {
tab +="<td>" + params[k] + "</td>";
}
tab +="</tr>";
}
tab +="</table>";
document.write(tab);
};
</script>
</head>
<body onLoad = "onStart()">
</body>
What's the problem?
Your for loops seem to be mis-indented and not closed properly
for(j = 0; j<headers.length;j++) {
tab += "<th>" + headers[j] + "</th>";
for(var j = 0; j < list.length; j++) {
var params = list[i].split('-');
tab += "<tr>";
for(k = 0; k < params.length;k++) {
tab +="<td>" + params[k] + "</td>";
}
tab +="</tr>";
}
Should be
for(j = 0; j<headers.length;j++) {
tab += "<th>" + headers[j] + "</th>";
}
for(var j = 0; j < list.length; j++) {
var params = list[i].split('-');
tab += "<tr>";
for(k = 0; k < params.length;k++) {
tab +="<td>" + params[k] + "</td>";
}
tab +="</tr>";
}
Not directly related to your question, but you have a few other common javascript errors.
By not declaring variables with var, you are unintentionally creating global variables. While this probably isn't a huge issue on your page, but it is bad practice.
In addition, you should wrap your <th> tags you are appending inside of a <tr>, as the only "valid" element within a <table> is a <tr> (technically its tbody, thead, and tfoot, of which the only valid children is <tr>).
You're missing the closing } on your first loop:
for(j = 0; j<headers.length;j++) {
tab += "<th>" + headers[j] + "</th>";
}
I would go to guess he is trying to loop thru headers, followed by columns, then close the table. Not loop thru headers, and for each header add all rows. And, certainly not loop thru headers and for each header loop through all rows and close and write the table.
In your code onStart(){} method is not closed properly. Add one more "}" in front of the below code
</script>
</head>

Creating a loop that populates a select tag

function buildOrder(data) {
var $fragment;
$fragment = $('<div/>');
for (var i = 0; i < data.length; i++) {
$fragment.append('<div class="row-container"><div class="row cupcake-row">' + data[i].name + '</div><div class="clear"></div></div>');
}
$('#review-section').append($fragment);
}
I essentially want to add a tag with 50 options being dynamically created using a for loop. But I'm not sure what the syntax would be to add it to the <div class="row-container"/> I know in php I would just throw the loop in the middle and echo the options, however that doesnt work in javascript.
EDIT:
It would look like this:
$fragment.append('<div class="row-container"><div class="row cupcake-row">' + data[i].name + '</div><select><option value="1">1</option> etc...</select><div class="clear"></div></div>');
You could pass a function to .append and do your loop there:
$("<div>").append(function() {
var $select = $("<select>");
for(var i = 1; i <= 50; i++) {
$("<option>").text(i).val(i).appendTo($select);
}
return $select;
});
// returns a jQuery object with one div element (with children):
// <div>
// <select>
// <option value="1">1</option>
// ...
// </select>
// </div>
Mixed into your code it would be along the lines of:
var $fragment = $("<div>");
for (var i = 0; i < data.length; i++) {
var $container = $("<div>").addClass("row-container")
.appendTo($fragment);
$("<div>").addClass("row cupcake-row")
.text(data[i].name)
.appendTo($container);
$("<div>").append(function() {
var $select = $("<select>");
for(var i = 1; i <= 50; i++) {
$("<option>").text(i).val(i).appendTo($select);
}
return $select;
}).appendTo($container);
$("<div>").addClass("clear")
.appendTo($container);
}
$("#review-section").append($fragment);
Try something like this
function buildOrder(data) {
var $fragment = $('<div></div>');
var options = [];
for (var i = 0; i < data.length; i++) {
options.push('<div class="row-container"><div class="row cupcake-row">' + data[i].name + '</div><div class="clear"></div></div>');
}
$fragment.html(options.join("\n"));
$('#review-section').append($fragment);
}
According to your posted code:
function buildOrder(data) {
var $fragment;
$fragment = '<div><div class="row-container">';
for (var i = 0; i < data.length; i++) {
$fragment += '<div class="row cupcake-row">' + data[i].name + '</div><div class="clear"></div>';
}
$fragment += '</div></div>';
$('#review-section').append($fragment);
}
But in your posted code doesn't match with your post title, where you mentioned about select tag and in your code you're trying with div.
If you want to create a select, then something like:
function buildOrder(data) {
var $fragment;
$fragment = '<div class="row-container"><select>'; // taking select within your div
for (var i = 0; i < data.length; i++) {
// adding options to select
$fragment += '<option value="'+ data[i].name +'">' + data[i].name + '</option>';
}
$fragment += '</select></div>'; // end select and div
$('#review-section').append($fragment);
}

Categories

Resources