This question already has answers here:
Adding onClick event dynamically using jQuery
(7 answers)
Closed 8 years ago.
I want to fetch the json data from serve and then loop the rows of table. the html code is like:
<table id="topics_list_table">
<thead>
<tr><th>Topic Title</th>
<th>Author Name</th>
<th>Likes</th>
<th>Created Time</th>
<th>Actions</th>
</tr></thead>
<tbody>
</tbody>
</table>
the jQuery part:
$.ajax({
url: some url here,
type:'GET',
success:function(res){
$.each(res, function(index, value){
$('#topics_list_table > tbody:last').
append(
"<tr>" +
"<td>" + value.title + "</td>"+
"<td>" + value.author_name + "</td>"+
"<td>" + value.likes + "</td>"+
"<td>" + value.created + "</td>"+
"<td>" +
"<a href='/components/topics/" + value.id + "' class='mini ui black buttons' id='detail_check'>check</a>"+
"</td>"+
"</tr>"
);
});
}
});
I could get all the data from the remote side, but the key question is this part
<a href='/components/topics/" + value.id + "' class='mini ui black buttons' onclick='somefunction()'>check</a>
I inspect this page and found, sth like
<a href="/components/topics/53cf67fad0c0f7fdda3ef8d5" class="mini ui black buttons" onclick='somefunction()'>check</a>
already exists in the dom.
but
1, the style class="mini ui black buttons" can not be applied.
2, when you try to click the "check" and want to trigger the somefunction(). it doesnt work.
so, why couldn't i get the dom element after appending the rows? OR, is there any other better way to loop rows after fetching the data?
thx
onclick attributes only work in the initial HTML, not in appended elements. See this question.
Instead, add the event handler using .click() or .on('click'):
success:function(res){
$.each(res, function(index, value){
var $row = $("<tr>" +
"<td>" + value.title + "</td>"+
"<td>" + value.author_name + "</td>"+
"<td>" + value.likes + "</td>"+
"<td>" + value.created + "</td>"+
"<td>" +
"<a href='/components/topics/" + value.id + "' class='mini ui black buttons' id='detail_check'>check</a>"+
"</td>"+
"</tr>");
$row.find('.mini.ui.black.buttons').on('click',somefunction);
$('#topics_list_table > tbody:last').
append($row);
});
}
Or, if it's the same function for every such link, just add it using event delegation:
$('#topics_list_table').on('click', '.mini.ui.black.buttons', somefunction);
Related
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 3 years ago.
I am currently working on a web application that needs to preview some report using a button inside a data table. each row on the data table has its own button created on the javascript and I want to trigger that button using the same javascript file.
Is there anyway to do this? Please see code below:
$('#AccountList').append('<tr data-empid="' + row.ci_ID + '">'
+ '<td text-align:center;">' + row.ciCODe + '</td>'
+ '<td text-align:center;">' + row.FullName + '</td>'
+ '<td text-align:center;">' + row.LoanType + '</td>'
+ '<td text-align:center;">' + row.Bank + '</td>'
+ '<td text-align:center;">' + row.Amount + '</td>'
+ '<td text-align:center;"><label class="'+ xLabel +'"><h6>' + xText + '</h6></label></td>'
+ '<td text-align:center;"><button class="btn btn-primary btn-outline-primary" id="btnPreview" name="btnPreview"><i class="icofont icofont-prescription"></i></button>'
+ '<button class="btn btn-danger btn-outline-danger" id="btnReinvestigate" name="btnReinvestigate"><i class="icofont icofont-redo"></i></button>'
+'</td>'
+ '</tr>');
$("#btnReinvestigate").click(function(){
alert("Hello Worlds!");
});
$("#btnPreview").click(function(){
alert("Hello World!");
});
Thanks and Regards
Appending rows where elements share the same id is semantically invalid.
In fact, you can do away with the id attribute on the buttons and instead utilise the name attribute.
You'll then want to delegate your click handlers to #AccountList
$('#AccountList')
.on('click', 'button[name="btnReinvestigate"]', function () {
alert('Reinvestigate')
})
.on('click', 'button[name="btnPreview"]', function () {
alert('Preview')
});
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I have a table field which I populate dynamically.
<table id="list" class="table table-striped ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header">
<th>Id</th>
<th>Name</th>
<th>Type</th>
<th>Expression</th>
<th>Variable</th>
<th>Default</th>
<th>Date pattern</th>
<th>Readable</th>
<th>Writable</th>
<th>Required</th>
</tr>
</thead>
<tbody>
</tbody>
I populate it with data I get from a dialog modal.
This is a function I use to populate the table
$("#list tbody").append("<tr>"+
"<td>" + id.val() + "</td>" +
"<td>" + name_re.val() + "</td>" +
"<td>" + type.val() + "</td>" +
"<td>" + expression.val() + "</td>" +
"<td>" + variable.val() + "</td>" +
"<td>" + defaut.val() + "</td>" +
"<td>" + pattern.val() + "</td>" +
"<td>" + readable + "</td>" +
"<td>" + writable + "</td>" +
"<td>" + required + "</td>" +
"<td>" +"<button type='button' class='removebutton' title='Remove this propertie'>"+"</button>" +
"<button type='button' class='editbutton' title='Edit this propertie'>"+"</button>" +
"<button type='button' class='savebutton' title='save propertie changes'>"+"</button>" +"</td>"+
"</tr>"
);
Now I created a function to get the data from the table and push them into an array of objects, as each object represent the data of a single row from the table.
This is the function I use to get the data
function getPropertiesListData(){
var propertiesList=[];
var id,
type,
expression,
variable,
defaut,
pattern,
readable,
writable,
required,
name;
$("#list").find('tr').each(function(){
var $tds=$(this).find('td');
propertiesList.push({
id:$tds.eq(0).text();
name:$tds.eq(1).text();
type:$tds.eq(2).text();
expression:$tds.eq(3).text();
variable:$tds.eq(4).text();
defaut:$tds.eq(5).text();
pattern:$tds.eq(6).text();
readable:$tds.eq(7).text();
writable:$tds.eq(8).text();
required:$tds.eq(9).text();
});
});
return propertiesList;}
But when I run, I have this error in the output of the navigator console
Uncaught SyntaxError: Unexpected token ;
this error is about the line:
id:$tds.eq(0).text();
Can you help me to resolve this, or tell me where I'm wrong, or tell me a way to get the data from the table and store them into an array.
Change your code like this:
propertiesList.push({
id:$tds.eq(0).text(),
name:$tds.eq(1).text(),
type:$tds.eq(2).text(),
expression:$tds.eq(3).text(),
variable:$tds.eq(4).text(),
defaut:$tds.eq(5).text(),
pattern:$tds.eq(6).text(),
readable:$tds.eq(7).text(),
writable:$tds.eq(8).text(),
required:$tds.eq(9).text(),
});
Try the following solution:
$("#list tbody").append("<tr>"+
"<td>1</td>" +
"<td>test</td>" +
"<td>test-type</td>" +
"<td>test-expr</td>" +
"<td>test-val</td>" +
"<td>test-def</td>" +
"<td>test-patt</td>" +
"<td>test-r</td>" +
"<td>test-w</td>" +
"<td>test-req</td>" +
"<td>" +"<button type='button' class='removebutton' title='Remove this propertie'>"+"</button>" +
"<button type='button' class='editbutton' title='Edit this propertie'>"+"</button>" +
"<button type='button' class='savebutton' title='save propertie changes'>"+"</button>" +"</td>"+
"</tr>"
);
function getPropertiesListData(){
var propertiesList=[];
var id,
type,
expression,
variable,
defaut,
pattern,
readable,
writable,
required,
name;
$("#list").find('tr').each(function(){
var $tds=$(this).find('td');
propertiesList.push({
"id":$tds.eq(0).text(),
"name":$tds.eq(1).text(),
"type":$tds.eq(2).text(),
"expression":$tds.eq(3).text(),
"expression":$tds.eq(4).text(),
"defaut":$tds.eq(5).text(),
"pattern":$tds.eq(6).text(),
"readable":$tds.eq(7).text(),
"writable":$tds.eq(8).text(),
"required":$tds.eq(9).text(),
});
});
return propertiesList;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="list" class="table table-striped ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header">
<th>Id</th>
<th>Name</th>
<th>Type</th>
<th>Expression</th>
<th>Variable</th>
<th>Default</th>
<th>Date pattern</th>
<th>Readable</th>
<th>Writable</th>
<th>Required</th>
</tr>
</thead>
<tbody>
</tbody>
The solution of #Himanshu Upadhyay works fine for me, i just deleted the last comma and that works.
The code that work is:
propertiesList.push({
id:$tds.eq(0).text(),
name:$tds.eq(1).text(),
type:$tds.eq(2).text(),
expression:$tds.eq(3).text(),
variable:$tds.eq(4).text(),
defaut:$tds.eq(5).text(),
pattern:$tds.eq(6).text(),
readable:$tds.eq(7).text(),
writable:$tds.eq(8).text(),
required:$tds.eq(9).text()
});
I want to make the link from during dynamic populating the table using Jquery. I am populating the table data as
trHTML +=
'<tr><td>'+ value['value1'] +
'</td> <td>' + value['value2'] +
'</td> <td>' + value['value3'] +
'</td><td>'.html('' + "Link" + '')+
'</td></tr>';
But it gives error
Uncaught TypeError: "</td><td>".html is not a function
You don't need to use .html() continue string concatenation.
'</td><td>' + '' + "Link" + ''+
However, I would recommend you to create HTML using jQuery( html, attributes ) method for cleaner approach.
var tr = $("<tr>")
var anchor = $("<a>", {
"href" : "http://www.google.com/" + value['valueLink'],
"text" : "Link"
});
var td = $("<td>");
td.append(anchor);
tr.append(td);
I have some jQuery script in which I'm adding some rows to a table (when the user press a button). My problem is that I want to change the id of the elements inside the rows dynamically. I have set a global variable i which I set as an id to some elements inside my table. The problem is that after some debugging I found out that the id doesn't change at all and stays as the letter i (and not the variable i set to 0 and increase every time the user press the button). Any ideas?
var i=0;
var a1=i.toString().concat("1");
var a2=i.toString().concat("2");
var a3=i.toString().concat("3");
$("#table1").append("<tr><td><center><input id=\"a1\"></input></center></td><td>
center><button id=\"a2\">Load</button></center></td><td ><img id=\"a3\"></td>
</tr>");
$("#a2").click(function(){
$z=$("#a1").val();
$("#a3").attr("src",$z);
i++;
});
That's because you're writing those directly as strings. You need to concatenate them into the actual string. You can concatenate strings together using +.
$("#table1").append(
"<tr>" +
"<td>" +
"<center><input id=\"" + a1 + "\" /></center>" +
"</td>" +
"<td>" +
"<center><input id=\"" + a2 + "\" /></center>" +
"</td>" +
"<td>" +
"<center><input id=\"" + a3 + "\" /></center>" +
"</td>" +
"</tr>"
);
For what it's worth, the <center> tag is deprecated and should not be used. You may also consider creating some kind of template rather than generating your HTML as strings directly inside of JavaScript.
I have a Html Table which displays data and is having delete and update functionality as below,
function DesignBTable(data) {
$("#ExpTableBody tr").remove();
var rowIndex = 0;
$.each(data, function (index, value) {
var fromDt = moment(value.from_date).format("MMM/YYYY");
var toDt = moment(value.to_date).format("MMM/YYYY");
$("#ExpTableBody").append("<tr>" +
"<td>" + value.org_name + "</td>" +
"<td>" + fromDt + "</td>" +
"<td>" + toDt + "</td>" +
"<td>" + value.designation + "</td>" +
"<td>" + value.location + "</td>" +
"<td>" + value.is_relevant + "</td>" +
"<td>" + '<input type="button" value = "X" class="btn btn-danger btn-sm" onClick="Javacsript:deleteRow(\'' + value.exp_id + '\',\'' + value.from_date + '\')">' + ' ' +
'<input type="button" value = "E" class="btn btn-info btn-sm" onClick="Javacsript:editRow(\'' + value + '\')">' + "</td>" +
"</tr>");
//alert(moment(value.from_date).format("MM/YYYY"));
rowIndex++;
});
};
The value object contains various fields.
On the Click event of the delete button I send value.exp_id and value.from_date as parameter to deleteRow function.
I want to add Edit functionality where if I click on the edit button it should send the value as object so that I can access all the fields in it.
When I try to send value as parameter to the JS function it errors out as undefined.
To create a string for code that uses the object, you would need to create a string representation of the object:
... onClick="editRow(' + JSON.stringify(value) + ')" ...
(Note: The JSON object is not supported in some older browsers.)
If you create elements directly instead of creating a string that you create elements from, you can bind the event directly and use the object without creating a string representation of it:
$("#ExpTableBody").append(
$("<tr>").append([
$("<td>").text(value.org_name),
$("<td>").text(fromDt),
$("<td>").text(toDt),
$("<td>").text(value.designation),
$("<td>").text(value.location),
$("<td>").text(value.is_relevant),
$("<td>").append([
$("<input>", { type: "button", value: "X", className: "btn btn-danger btn-sm" }).click(function(){
deleteRow(value.exp_id, value.from_date)
}),
$("<input>", { type: "button", value: "E", className: "btn btn-info btn-sm" }).click(function(){
editRow(value);
})
])
])
);
As a side effect, by using the text method to put the values in the cells, it's protected agains script injection. If you actually have HTML code that you want to put in a cell, you would use the html method instead. That naturally means that you should encode it properly when you create that HTML code to protect against script injection.
Side note: The javascript: pseudo protocol is only used when you put code in an URL, i.e. a href attribute. If you use it anywhere else it becomes a label instead. This is not harmful, but useless and confusing.
the problem of 'value' accessibility is it's defined only inside the function not outside.
I see you use JQuery, so you can use JQuery.data to make a link between an html object and a custom value. In your case you can add the value directly to the button at the end of the row.