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')
});
Related
So I got into this tricky situation. I have a variable which present table data:
row += '<td>' + c + '<button class="btn btn-success" id="' + callId + ' " onclick="handleCall()">Call</button>' + '<button class="btn btn-danger" id="' + hangupId + ' " onclick="handleHangUp()">Hangup</button>' + '</td>' ;
Latter on I will append that into my table. Now, when I click Call button, I want to get the button's Id. I have tried this way:
function handleClick() {
console.log(this);
}
but it refer to window object. Can anybody show me the way to achieve my goal? Thanks
Simply pass the elements ID as a parameter to keep it simple,
Change,
onclick="handleCall()"
to,
onclick="handleCall(this.id)"
this referring to the button in question the user is pressing.
then,
function handleClick(id) {
console.log(id);
}
Finally don't use inline event handlers as they are a pain to work with in the long run, make use of the addEventListener method.
row += '<td>' + c + '<button class="btn btn-success" id="' + callId + ' " onclick="handleCall(this)">Call</button>' + '<button class="btn btn-danger" id="' + hangupId + ' " onclick="handleHangUp()">Hangup</button>' + '</td>' ;
function handleClick(element) {
console.log(element);
//here you will have all element properties
}
There are two ways you can do this, you can do it via jQuery by using attr or if you are wanting to stay vanilla Javascript then you can use .id.
For jQuery please see code below:
console.log(jQuery('element').attr('id'));
For Javascript please see code below:
console.log(element.id);
i am creating a search suggestion and i want to create a div and put suggestion elements like full name, image and ... in it.
so i have a empty div in my HTML code that my suggestions will be added to it.
<input type="text" name="query" autocomplete="off" id="base_main_search_box">
<button type="button" value="" id="base_main_search_box_button"></button>
<div id="main_searchSuggestion">
</div>
i want to appear search suggestions when user key up in input type.
so i create jQuery function.
my jQuery function is:
$('#base_main_search_box').keyup(function () {
$.ajax({url:'http://localhost:8000/search_suggestion/',success:function(result){
$(addSuggestion).append('<div class="base_searchSuggestionItem">' +
'<img src="' + result.movie_images[i] + '" class="base_searchSuggestionItem_image">' +
'<div class="base_searchSuggestionItem_info">' +
'<p class="base_searchSuggestionItem_info_name">' +
'<a href="">' +
result.movie_names[0] +
'</a>' +
'(' +
result.movie_yearProduction[0] +
')' +
'</p>' +
'<p class="base_searchSuggestionItem_info_description">' +
result.movie_descriptions[0] +
'</p>' +
'</div>' +
'</div>');
console.log('final: '+addSuggestion.innerHTML);
}
}});
});
the output is:
"final: undefined"
it is not correct.
As per the docs
.html() is not available on XML documents so you need to add it to DOM before setting or checking its HTML.
change the sequence as following
$(addSuggestion).append(search_item);
$(search_item).html(
div_innerHTML
);
console.log('div_innerHTML: '+div_innerHTML);
console.log('search_item: '+$(search_item).innerHTML);
I am building a string and creating a table with it:
table += '<td>'+ '<a href="#" onclick="portal_openModalDialog();" >'+ oListItem.get_item('Title') +'</a>' + '</td>'
When I click the link, the function fires.
I need to pass some Javascript variables in the function VarTest() so I've written the code:
table += '<td>'+ '<a href="#" onclick="portal_openModalDialog('+ VarTest + ');" >'+ oListItem.get_item('Title') +'</a>' + '</td>'
But nothing happens, I've tried all sorts of options but nothing works.
This works (with +) but then nothing gets passed.
table += '<td>'+ '<a href="#" onclick="portal_openModalDialog('+')" >'+ oListItem.get_item('Title') +'</a>' + '</td>'
var VarTest = "my text";
function portal_openModalDialog(Title) {
alert(Title);
}
Any ideas?
UPDATE: (this now works for single argument)
table += '<td>'+ '<a href="#" onclick="portal_openModalDialog1("'+oTitle+'")" >'+ oListItem.get_item('Title') +'</a>' + '</td>';
but not if I pass 2 arguments:
table += '<td>'+ '<a href="#" onclick="portal_openModalDialog1("'+oTitle,oDescription+'")" >'+ oListItem.get_item('Title') +'</a>' + '</td>';
The html gets rendered on the screen:
<a href="#" onclick="portal_openModalDialog1("Bank of England</tr><tr><td><img src='../Style Library/Icons/Noticeboard_News.png' /></td><td><a href="#" onclick="portal_openModalDialog1("Investor centre - Reed Elsevier</tr><tr><td><img src='../Style Library/Icons/Noticeboard_News.png' /></td><td><a href="#" onclick="portal_openModalDialog1("This is some news</tr></table> </body>
Here is source code of html page (cant see why it would not render correctly):
table += '<td>'+ '<a href="#" onclick="portal_openModalDialog1("'+oTitle+'")" >'+ 'click here' +'</a>' + '</td>';
table += ''+ ''+ 'click here' +'' + '';
The content of onclick attribute is parsed as JavaScript. You can just pass the variable, no magic involved:
<script>
var myVar = 'foo';
function myFunction(aVar) {
alert('The variable: ' + aVar);
}
</script>
<button onclick="myFunction(myVar)">Click me</button>
You can pass multiple variables, just make sure that the comma (,) is part of the resulting HTML and not a comma in the original JavaScript code:
<script>
var myFirstVar = 'foo';
var mySecondVar = 'bar';
function myFunction(aVar, anotherVar) {
alert('The first variable: ' + aVar + ', and the second: ' + anotherVar);
}
</script>
<button onclick="myFunction(myFirstVar, mySecondVar)">Click me</button>
If you want to generate the button in the page, and you are sure your variables are meant to be strings, you can keep quoting the parameters:
document.write('<button onclick="myFunction("' + myFirstVar + '", "' + mySecondVar + '")">Generated button 1</button>');
But, it is easier and less error prone to just pass the variables directly:
document.write('<button onclick="myFunction(myFirstVar, mySecondVar)">Generated button 2</button>');
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);
I'm trying to create a dynamic table which will have rows added and removed throughout its use. I do not want to have to put id's on every container that I later want to reference.
For instance, I want to add a hidden input to the last cell of a dynamically added row. The row has an id, how can I use dojo.place() when I do not have an id on the last cell?
var pmrCount = dojo.query("#pmhTable >tbody >tr").length;
var rowID = 'pmr_' + pmrCount;
var newPmrRow =
'<tr id="' + rowID + '">' +
'<td>' + pmh + '</td>' +
'<td>' + String(pmr.severity).charAt(0) + '</td>' +
'<td>' + pmr.customerName + '</td>' +
'<td>' + pmr.deviceType + '</td>' +
'<td>' + pmr.deviceModel + '</td>' +
'<td>' + pmr.deviceSerial + '</td>' +
'<td align="center"><a class="cancel-link"></a></td>' +
'</tr>';
//dojo.place(newPmrRow, dojo.query("#pmhTable >tbody"));
var newPmrHiddenInput =
'<input type="hidden" name="pmrs" value="'+ JSON.stringify(pmr)+ '">';
//dojo.query("#" + rowID + " td:last").place(newPmrHiddenInput);
The two commented lines of code are the ones that I am trying to replace with functional code. These do not work, they don't surface any warnings in the error console like other syntax errors. Not sure where to go from here.
I know that dojo.query() returns a NodeList and place() is expecting an DOM node or an id. What's the correct way to do this?
You want to look at the dojo/NodeList-dom extension to Nodelist. It allows you to place each element in a NodeList into an element based on query selector . In AMD Style it looks like:
require(['dojo/dom-construct', 'dojo/NodeList', 'dojo/NodeList-dom', 'dojo/domReady!'], function (domConstruct, NodeList) {
var nodes = new NodeList([domConstruct.toDom('<div>someContent</div>')]);
nodes.place('#x');
});
Looking at the docs I was kind of surprised there wasn't an easier way to do this, so maybe there is a better way than this.
Well, I found two lines of code that seem to work, but I don't know if referencing NodeLists in an Array style is technically correct for this. This is what I did.
dojo.place(newPmrRow, dojo.query("#pmhTable >tbody")[0]);
dojo.place(newPmrHiddenInput, dojo.query("#" + rowID + "> td:last-child")[0]);