jQuery .click() not working? - javascript

I generate the set of buttons within html table as follows and then I want to call to function when it click.
$.each(childData, function(key, item) {
var packPath = key.replace(/_/g, "/"); //Replace underscore with slash
div.innerHTML = div.innerHTML + '<td>'+key+'</td>'
+ '<td><button type="button" data-id="'+key+'" class="download btn btn-success btn-xs">Originals</li></td></div>';
})
This is how I call the function but it's not working.
$(".download").click(function(){
alert();
});
Where is the wrong in above code?

Try this:
$(document).on('click', '.download', function(){
// Your Code
});

Delegate the event to static parent:
$(div).on("click", ".download", function(){
Here div can be the static parent which was available when page was loaded at first load. Although document or body can also be used in place of div.
As you have not presented how you create div element but one thing has to be noticed that you are generating an invalid markup. As a td element can't be a child of div but table's tr.

You need to use event delegation.
If your table has an id of "button-table", you can create an event handler like so:
$("#button-table").on("click",function(e){
var target = e.target;
console.log($(target).attr("data-id"));
});

Do you want it this way? I have given code for adding an entire table.Check this out
function generate_table() {
// get the reference for the body
var body = document.getElementsByTagName("body")[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
// creating all cells
for (var i = 0; i < 2; i++) {
// creates a table row
var row = document.createElement("tr");
for (var j = 0; j < 2; j++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
var cellText = document.createTextNode("cell in row "+i+", column "+j);
cell.appendChild(cellText);
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
}
<input type="button" value="Generate a table." onclick="generate_table()">

$(document).ready(function() {
$(".download").click(function(){
alert();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="downlaod">Download</button>

Related

How to select thead element from dynamically built table?

I have dynamically built table in JavaScript/JQUERY. After table is built I need to select thead element. Here is example of my code:
$(document).ready(function(){
buildTbl();
});
function buildTbl() {
var tbl = '<table id="myTbl"><thead><tr><th>Column 1</th></tr></thead><tr><td>Cell 1</td></tr><tbody></tbody></table>';
$('#tblContainer').empty().append(tbl);
var test = $('#myTbl').find('thead');
console.log(test);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='tblContainer'></div>
As you can see in example in console length is 0. The element is not selected. I'm wondering how I can access dynamically built elements in JavaScript? I need to prevent headers from scrolling so that's why I need to select thead element int he table.
In your case I suggest you another way of creating your element. As you are using jquery you can use jquery to create your html node as follow so that you can access to your jquery element before appending it into the dom:
$(document).ready(function(){
buildTbl();
});
function buildTbl() {
var $tbl = $("table").attr("id", "myTbl");
var $thead = $("thead");
// TODO: Here you can add your table rows into your thead
$tbl.append($thead);
// now you can access to your thead element without searching the dom.
console.log($thead);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You need to append it to the dom before you want to retrieve it using selector
$(document).ready(function() {
buildTbl();
});
function buildTbl() {
var tbl = '<table id="myTbl"><thead><tr><th>Column 1</th></tr></thead><tr><td>Cell 1</td></tr><tbody></tbody></table>';
$('#tableContainer').append(tbl)
var test = $('#myTbl').find('thead');
console.log(test);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='tableContainer'></div>
Try This and call buildTbl before $(document).ready()
function buildTbl() {
var tbl = '<table id="myTbl"><thead><tr><th>Column 1</th></tr></thead><tr><td>Cell 1</td></tr><tbody></tbody></table>';
$('#tableContainer').html(tbl)
}
$(document).ready(function(){
buildTbl();
var test = $(document).find('#myTbl > thead');
console.log(test);
});
And call the div with id tableContainer
Hope this will help you

Replacing entire DIV with function

I'm attempting to start a div area with html in it and then replace that html with new html. I am currently trying to do so with the use of a function to simplify the creation of the html.
This is my function that creates a table based on input of rows and columns and a character.
function drawArt (x, y, char){
$( "#artArea").append("<table>");
indexY = 0;
while (indexY < y)
{
$( "#artArea").append("<tr>");
var indexX = 0;
while (indexX < x)
{
$( "#artArea").append("<td class=tableCell>" + char + "</td>");
indexX++;
}
$( "#artArea").append("</tr>");
indexY++;
}
$( "#artArea").append("</table>")
};
I'd like to be able to recall this function to redraw the table. So far this is what I have written but it seems to not work. Any tips?
$( "#genNew" ).click(function(){
var xGlobal = $("#numCols").val();
var yGlobal = $("#numRows").val();
var charGlobal = $("#drawChar").val();
$( "#artArea" ).replaceWith();
drawArt (xGlobal, yGlobal, charGlobal);
})
So, as suggested below changing "replaceWith" to "empty" fixed part of my problem. However, it broke another part of my program. I should be able to click on any character and get it to change to whatever was input, without changing the whole table, as so:
$( ".tableCell" ).click(function(){
charGlobal = $("#drawChar").val();
$(this).text(charGlobal)
})
Which part of my program is failing?
The big problem is you're creating invalid html. You always append to the #artArea table, so your markup will end up as
<table>
<tr></tr>
<td></td>
<td></td>
... etc
</table>
This is not what you want. What I suggest you could do is to simply create the appropriate html as a string inside drawArt and use `replaceWith to change the html
function drawArt (x, y, char){
var html = "<table>";
indexY = 0;
while (indexY < y)
{
html += "<tr>";
//-- snip, you get the idea!
}
html += "</table>"
return html;
}
and then
$( "#genNew" ).click(function(){
var xGlobal = $("#numCols").val();
var yGlobal = $("#numRows").val();
var charGlobal = $("#drawChar").val();
$( "#artArea" ).html(drawArt (xGlobal, yGlobal, charGlobal));
})
Working example: http://jsfiddle.net/0sh1wt01/1/
Having updated the question with a new requirement, I should address that too. The reason your click event handler does not work on the table cells is that click only affects elements which are on the page at the time the page loads. if you're dynamically adding new elements (as we are above) then you need to delegate the event to an element which does exist at page load. In this case we could use the artArea. Note you want .html not .text
$( "#artArea" ).on('click','.tableCell', function(){
charGlobal = $("#drawChar").val();
$(this).html(charGlobal);
});
Live example: http://jsfiddle.net/0sh1wt01/2/
You can replace the html with a new one.
This is the js code:
$("#start").click(function() {
var x = $("#rows").val(),
y = $("#columns").val(),
charx = $("#char").val();
//getting teh no of columns, rows and the character
$("#container").html("");
//empty the container first
var table = document.createElement("table");
for (var i = 0; i < x; i++) {
var tr = document.createElement("tr");
for (var j = 0; j < y; j++) {
var td = document.createElement("td");
td.innerHTML = charx;
tr.appendChild(td);
}
table.appendChild(tr);
}
//creating the table based on the values
$("#container").append(table);
//appending inside the container
});
Here is the Plnkr Link
Hope it works for you :)

Adding Table Rows on Button Click

I want to add table rows as the user clicks the Add button. In a new row there are 3 textboxes. As the rows gets added id of textboxes should be set like array list.
For e.g
if it is 2nd row added, the textbox ids will be textbox1_1 textbox2_1 textbox3_1
if it is 3rd row added, the textbox ids will be textbox1_2 textbox2_2 textbox3_2
Because I want to Add all these textboxes values in a single string at the end.
FIDDLE
Added later :-
Indeed at the first time there are no rows in the table.
try this:
$("#btnAdd").click(function(){
var id = $('table tr').size(),
i,
row = '<tr>';
for(i = 1; i <= 3; i++) {
row += '<td><input type="text" id="text'+i+'_'+id+'" />';
}
row += '</tr>';
$('table').append(row);
});
DEMO
Alternativly if you want to build from previous rows you can do this:
$("#btnAdd").click(function(){
var id = $('table tr').size(),
tr = $('table tr').last().clone();
$(tr).find('td').each(function (index) {
$(this).attr('id', 'text'+index+'_'+id);
});
$('table').append(tr);
});
DEMO
Try this : you can add row by cloning first row and updating each input's id by iterating them.
//get the count of available row in table
var count = $('#dynamicTable tr').length;
$("#btnAdd").click(function(){
//clone the first row in table
var $tr = $('#dynamicTable tr:first').clone();
//iterate each input to change its id
$tr.find('input').each(function(){
var id = $(this).attr('id');
id = id.substring(0,id.length-1);
$(this).attr('id',id+count);
});
// update count
count++;
//add row to the table
$('#dynamicTable').append($tr);
});
JSFiddle link
Try thus
$("#btnAdd").click(function(){
var rowCount = $("table tr").length;
var firstRow = $("table tr:first").clone();
firstRow.find("input").each(function(){
this.id=this.id.replace("_0","_"+rowCount);
});
$("table").append(firstRow);
});
DEMO
write less do more with jquery. use chaining as below
$("#btnAdd").click(function(){
$('table')
.find("tr:first") // traverse the first tr
.clone() // clone the row
.appendTo('table') // append the the table tag
.end() // reset to default selector
.find('input').each(function(i,x){
$(this).prop('id',this.id.split('_')[0]+'_'+(+$('table tr').length-1)); // assign the id to the added new row
});
});
EDIT done with FIDDLE too
Hope it helps....

How to id dom table so I can position it on page?

I am new to creating tables with js and started with using document.write. That was writing over my html so now I am using dom elements. How can I id the group of tables so I can position it in my css? I am a little confused how because my code creates multiple tables with the loop. I would just like to position them all as one. The picture shows what they look like but they just default to the bottom/left of my page. Also would appreciate any other code suggestions since I am new at this! Thanks!
<script type="text/javascript">
BuildTable();
function BuildTable() {
var myUrl = window.location.href;
PageMethods.DoStuff(myUrl, onSucess, onError);
function onSucess(result) {
for (var i = 0; i < result.length; i++) {
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
var row = document.createElement("tr");
var cell = document.createElement("td");
var cellText = document.createTextNode('Community: ' + result[i].apartName);
cell.appendChild(cellText);
row.appendChild(cell);
tblBody.appendChild(row);
row = document.createElement("tr");
cell = document.createElement("td");
cellText = document.createTextNode('Address: ' + result[i].address + ', ' + result[i].city);
cell.appendChild(cellText);
row.appendChild(cell);
tblBody.appendChild(row);
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "1");
var space = document.createElement("br");
body.appendChild(space);
}
}
function onError(result) {
alert('Something wrong.');
}
}
</script>
To set the id:
tbl.setAttribute('id', thisTablesId );
But probably what you want is to set the class attribute instead. Those don't need to be unique. You can change the css styles (for positioning) of all tables with the same class at once. Or if you need to programmatically determine the styling, you can use that attribute to determine whether or not this is one of the elements you wanted.
tbl.setAttribute('class', 'built-table' );
In your css stylesheet you can define what the built-table class will include using the .built-table selector.

javascript loop: variable equals the last iteration

The code below will add element once user clicks addmore link.
The problem arrives when the user clicks the remove link.
I have something like these on my code
<script language="JavaScript">
var count=1;
function addmore() {
alert(count);
var printme = "<table id='table"+count+"'><tr><td><a href='#' onclick='remove(count)'>remove</a></td></tr></table";
//(other code here)...
count++;
}
function remove(y) {
alert(y)
var tab = 'table'+y;
document.getElementById(tab).style.display = "none";
}
</script>
I used the alert here so I can easily monitor the value of count it gives.
What happens here is that the value of 'y' (on remove function) always the same, which is the last value of count in the loop.
For example I click the link addmore 3 times, therefore the last value of my 'count=4'.
And let say I wanted to remove the 3rd element which at this point when i clicked the remove link, it must have pass argument like this remove(3). But what happens here is whatever element i clicked it seems like it always passing argument this way remove(4)
That's because you have count as a global variable.
Try .....onclick='remove("+count+")'.... to sort of "lock in" the value.
Please try this:
var printme = "<table id='table"+count+"'><tr><td><a href='#' onclick='remove("+count+")'>remove</a></td></tr></table";
also try following line remove function:
document.getElementById(""+tab+"").style.display = "none";
All previous answers are correct, onclick refers to the current variable count when remove is called.
When you generate the text for the table you use the value of count as it is then:
onclick='remove('+count+')...
You can leave out the id's and count altogether using this:
onclick='remove(this.parentElement.parentElement.parentElement);'...
function remove(elementToRemove){
elementToRemove.parentElement.removeChild(elementToRemove);
}
maybe just onclick='remove('+count+')'
You can do something like
<html>
<head>
<script type="text/javascript">
var count=1;
function addmore() {
var id = 'table' + count;
var table = document.createElement('table');
table.setAttribute('id', id);
var tr = document.createElement('tr');
var td = document.createElement('td');
var a = document.createElement('a');
a.setAttribute('href', '#');
a.appendChild(document.createTextNode('remove ' + id));
a.onclick = function() {
table.style.display = 'none';
document.body.removeChild(table);
};
td.appendChild(a);
tr.appendChild(td);
table.appendChild(tr);
document.body.appendChild(table);
count++;
}
</script>
</head>
<body>
Add Table
</body>
</html>
With table reference and onclick defined like this you don't need id

Categories

Resources