When I'll click td get td text dynamic in jquery [duplicate] - javascript

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
i'm create table using javascript but i stuck when i'll click table td,get dynamically td text value in jquery without using for loop/each
function table_form(day, month, year) {
var tr = '';
var table = '<table id="tbl" border="1px"><thead><tr><th><</th><th>Mar</th><th>></th><th></th><th><</th><th>2016</th><th>></th></tr><tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th></tr></thead>';
//~ dynamic_date_form(2,2016);
var tr_inc = 0;
for (var i = 0; i < 5; i++) {
tr += '<tr>';
for (var j = 0; j < 7; j++) {
tr_inc++;
tr += '<td id="id_' + tr_inc + '">' + tr_inc + '';
}
}
tr += '</tr>';
tr_inc++;
return table += tr;
}
$(document).ready(function() {
$("#date_id").one("click", function() {
this.insertAdjacentHTML("afterEnd", "<div id='lbl_date'></div>");
$('#lbl_date').html(table_form(1, 1, 1));
});
$('#tbl').click(function() {
alert($(this).text());
});
});
#lbl_date{
position: absolute;
background-color:#FFAA41;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<input type="text" id="date_id" class="date" />
<label for="lbl_date">date</label>

You need event delegation for dynamically generated element like following.
$(document).on('click', '#tbl td',function(){
alert($(this).text());
});

Related

Add a header row and a time column to a generated HTML table with jQuery

I have these two working JavaScript functions
https://github.com/cryptomanxxx/Random2DArrayPlusHtmlTable
https://cryptomanxxx.github.io/Random2DArrayPlusHtmlTable/
that 1) generates some random data 2) creates a HTML table for such data. There are two problems.
1) The HTML table column headings (the first row in the HTML table) are missing. Which is the simples way to add a row (should be the first row) with column headings to the HTML table? The column heading row should say something generic like this: variable 1, variable 2, variable 3 etc etc
2) The HTML table does not have a column with timestamps. A new column (first column) with timestamps would also be nice like: time 1, time 2, time 3 etc etc
It is obvious that I have not managed to understand how the code works because if I did it would be easy to modify the code. The complexity is overwhelming.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="JavaS.js"></script>
<meta charset="utf-8" />
<style>
table {
border-collapse: collapse;
}
table,
td,
th {
border: 1px solid black;
}
</style>
</head>
<body>
<div id="div1">
</body>
<script> htmlTable(RandomArray(8, 4)); </script>
</html>
function RandomArray(rows, cols) {
var arr = [];
for (var i = 0; i < rows; i++) {
arr.push([]);
arr[i].push(new Array(cols));
for (var j = 0; j < cols; j++) {
arr[i][j] = Math.random();
}
}
console.log(arr);
return arr;
}
function htmlTable(d) {
var data = d;
var html = '<table><thead><tr></tr></thead><tbody>';
for (var i = 0, len = data.length; i < len; ++i) {
html += '<tr>';
for (var j = 0, rowLen = data[i].length; j < rowLen; ++j) {
html += '<td>' + data[i][j] + '</td>';
}
html += "</tr>";
}
$(html).appendTo('#div1') ;
}
Don't stress about the complexity, it gets easier the longer you play with it.
1) If you want column headers, that's what th tags are for... and they should go inside the thead tags you already have, like this:
var html = '<table><thead><tr><th>Timestamp</th><th>Variable 1</th><th>Variable 2</th><th>Variable 3</th><th>Variable 4</th></tr></thead><tbody>';
Read more about HTML tables here.
2) If you want an additional column, add in a value (a td - short for table data) before the loop that adds the randomize values
...
html += '<tr>';
html += '<td>' + new Date().getTime() + '</td>' <------ NEW CODE TO ADD ANOTHER VALUE
for (var j = 0, rowLen = data[i].length; j < rowLen; ++j) {
...
You can learn more about dates, both creating them and displaying them, here.
All said and done, your function would look like:
function htmlTable(d) {
var data = d;
var html = '<table><thead><tr><th>Timestamp</th><th>Variable 1</th><th>Variable 2</th><th>Variable 3</th><th>Variable 4</th></tr></thead><tbody>';
for (var i = 0, len = data.length; i < len; ++i) {
html += '<tr>';
html += '<td>' + new Date().getTime() + '</td>'
for (var j = 0, rowLen = data[i].length; j < rowLen; ++j) {
html += '<td>' + data[i][j] + '</td>';
}
html += "</tr>";
}
$(html).appendTo('#div1') ;
}

How to delete the selected file from array using JavaScript

I am trying to call the delete button to remove the listed file. Can anyone help me to build the logic.
$(document).ready(function () {
$('input[type = "file"]').change(function (e) {
var input = document.getElementById('fileUploader');
var output = document.getElementById('divFiles');
var HTML = "<table>";
for (var i = 0; i < input.files.length; ++i) {
HTML += "<tr><td>" + input.files.item(i).name + "</td><td> <button ></button></td></tr>";
}
HTML += "</table>";
output.innerHTML = HTML;
});
});
You can remove the parent tr tag containing button delete like
$('.btnDelete').on('click', function () {
$(this).closest('tr').remove();
});

Why Chrome adds tbody tag to each table row? [duplicate]

This question already has answers here:
Why do browsers insert tbody element into table elements?
(2 answers)
Why do browsers still inject <tbody> in HTML5?
(6 answers)
Closed 6 years ago.
I have two tables that fill up throw an event.
The stylesheet is made for that the even rows get painted white.
table {
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
But due Chrome adds tbody tag to each tr tag it's doesn't work.
The first table fill up throw back-end:
var prueba = {};
prueba = nuevaCadena[nuevaCadena.length - 1].replace(/<br>/g, "").split(",");
prueba.venta = prueba[0];
prueba.fecha = prueba[1];
prueba.heladeria = prueba[2];
//prueba.base.split(",");
//if (myElem === null) {
var contenido = document.getElementById("contenido");
var tr2 = document.createElement("TR");
if (contenido.getElementsByTagName("TH").length === 0)
{
contenido.appendChild(tr2);
tr2.innerHTML += "<th>Heladeria</th>";
tr2.innerHTML += "<th>Fecha</th>";
tr2.innerHTML += "<th>ID</th>";
} else {
var template = "<tr><td>{{heladeria}}</td><td>{{fecha}}</td><td>{{venta}}</td></tr>";
document.querySelector('#contenido').innerHTML += Mustache.render(template, prueba);
}
And the second works perfectly. It's fill up throw the select tag values.
var contenido = document.getElementById("contenido2");
var tr2 = document.createElement("TR");
var tr = document.createElement("TR");
if (contenido.getElementsByTagName("TH").length === 0)
{
contenido.appendChild(tr2);
tr2.innerHTML += "<th>Heladeria</th>";
tr2.innerHTML += "<th>Fecha</th>";
tr2.innerHTML += "<th>Sabor</th>";
tr2.innerHTML += "<th>Cantidad</th>";
}
contenido.appendChild(tr);
//var th = document.createElement("TD");
var option = ["heladerias", "sabores"];
var valor = document.getElementById("sabor_calorias");
var fecha = document.getElementById("fecha");
for (var i = 0; i <= 0; i++) {
var input = document.getElementById(option[i]).selectedIndex;
var input2 = document.getElementById(option[i]).options;
tr.innerHTML += "<td>" + input2[input].text + "</td>";
tr.innerHTML += "<td>" + fecha.value + "</td>";
for (var j = 1; j <= 1; j++) {
input = document.getElementById(option[j]).selectedIndex;
input2 = document.getElementById(option[j]).options;
tr.innerHTML += "<td>" + input2[input].text + "</td>";
tr.innerHTML += "<td>" + valor.value + "</td>";
tr.innerHTML += "<input type='button' class='borrar' value='x' onclick='deleted(this)'/>";
}
}
The results are this:
This question didn't work for me Why do browsers insert tbody element into table elements? i use Mustache.
When parsing the HTML syntax, the browser will insert a tbody tag, as explained in Why do browsers still inject <tbody> in HTML5?. By appending to the innerHTML each time, you're creating a new tbody each time. The HTML syntax can't represent a tr as a direct child of a table.
You could instead use
tr = table.insertRow()
tr.innerHTML='<td>foo<td>bar'
if you still wanted to write the row with innerHTML, or use td = tr.insertCell() as well.
The tags that chrome add are not needed, and shouldn't affect your code.
If you keep getting the error you might want to try going through to make sure you don't have any missed-placed characters.

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";
}

How to dynamically Add and Remove multiple <tr> with input fields

What i m trying to do is when the user type number quantity automatically jquery must create that number of with inputs.
so i used this code to generate
$( "#cont_qty" ).change(function()
{
var cont_qty = this.value;
for(var i=1 ; cont_qty>i; i++)
{
itemCount++;
// dynamically create rows in the table
var auto_tr = '<tr id="tr'+itemCount+'"><td><input class="input-medium" type="text" id="cont_no'+itemCount+'" name="cont_no'+itemCount+'" value=""></td></tr>';
$("#munna").append(auto_tr)
}
});
If the user type 5 then it creates 4 now if the user change the value and type 7 then have to remove the previous created those 4 and then have to create 6
now i dont know how to remove
Empty before looping, and start at zero
$( "#cont_qty" ).change(function() {
var cont_qty = this.value;
$("#munna").empty();
for(var i=0 ; cont_qty>i; i++) {
itemCount++;
var auto_tr = '<tr id="tr'+itemCount+'"><td><input class="input-medium" type="text" id="cont_no'+itemCount+'" name="cont_no'+itemCount+'" value=""></td></tr>';
$("#munna").append(auto_tr)
}
});
use Html() not append()
$("#cont_qty").change(function () {
var cont_qty = this.value;
var html = "";
for (var i = 1; cont_qty >= i; i++) {
itemCount++;
// dynamically create rows in the table
html += '<tr id="tr' + itemCount + '"><td><input class="input-medium" type="text" id="cont_no' + itemCount + '" name="cont_no' + itemCount + '" value=""></td></tr>';
}
$("#munna").html(html);
});
$( "#cont_qty" ).change(function()
{
var cont_qty = this.value;
var html = '';
for(var i=1 ; cont_qty>i; i++)
{
itemCount++;
// dynamically create rows in the table
html += '<tr id="tr'+itemCount+'"><td><input class="input-medium" type="text" id="cont_no'+itemCount+'" name="cont_no'+itemCount+'" value=""></td></tr>';
}
$("#munna").html(html);
});
To prevent it from creating one less than you want, change this:
for(var i=1 ; cont_qty>i; i++)
to this:
for(var i=1 ; i<=cont_qty; i++)
And, has already been stated, as you want to reset the amount of fields everytime you change the number, change $("#munna").append(html); to $("#munna").html(html);
$( "#cont_qty" ).change(function()
{
var cont_qty = this.value;
for(var i=1 ; cont_qty>i; i++)
{
itemCount++;
html += '<tr id="tr'+itemCount+'"><td><input class="input-medium" type="text" id="cont_no'+itemCount+'" name="cont_no'+itemCount+'" value=""></td></tr>';
}
$("#munna").html(html)
});
Beside of use 'append' the html div, .html can reload the div content.
change the whole html content of #munna with html()
$( "#cont_qty" ).change(function()
{
var cont_qty = this.value;
for(var i=1 ; cont_qty>i; i++)
{
itemCount++;
// dynamically create rows in the table
var auto_tr += '<tr id="tr'+itemCount+'"><td><input class="input-medium" type="text" id="cont_no'+itemCount+'" name="cont_no'+itemCount+'" value=""></td></tr>';
}
$("#munna").html(auto_tr)
});
You have to use .html() instead of .append() outside of your loop.
$("#munna").html(html);
Instead of
$("#munna").append(html);

Categories

Resources