Call a javascript function inside a dynamic row Jquery - javascript

Good day guys. I am trying to implement onclick function in a dynamically created table in jQuery. But each time I click the button, I get this error
(Unexpected token ILLEGAL)
in my console.
But when I click on the error, there's no code on the line it's pointing to.
Here is the code :
$(document).ready(function(){
var tbl="";
$.getJSON('./libs/form.php',function(result){
console.log(result);
$.each(result,function(key,val) {
if($.isNumeric(key)){
var mail=val.Email;
tbl+="<tr class='odd gradeX'> ";
tbl+="<td>" + val.Name + "</td>";
tbl+="<td>"+ val.Email +"</td>";
tbl+="<td>"+ val.Gender +"</td>";
tbl+="<td>" + val.Qualification + "</td>";
tbl+="<td>" + val.Experience + "</td>";
tbl+="<td>" + val.Note + "</td>";
tbl+="<td><a onclick='javascript:call(" + mail +");' class='btn btn-success btn-small'><i class='icon-edit icon-white'></i>" + "EDIT" + "</a></td>"
tbl+="</tr>";
}
});
$("#applicantstbl").append(tbl);
$("#applicantstbl").dataTable({
"bJQueryUI":true,
"sPaginationType":"full_numbers"
});
});
});
Please I'd like to know what am I doing wrong, it displays the table perfectly. Just the onclick function.
Here is the function am trying to call :
<script>
function call(name)
{
alert("Called"+ name);
}
</script>

Try changing
".....onclick='javascript:call(" + mail +");'...."
to
".....onclick='javascript:call(\"" + mail +"\");'....."

Try it like,
$('#applicantstbl').on('click','.mail-link',function(e){
e.preventDefault();
call($(this).data('email'));
});
Add a class mail-link to your html link like,
tbl+="<td><a data-email='"+mail+"' class='mail-link btn btn-success btn-small'><i class='icon-edit icon-white'></i>" + "EDIT" + "</a></td>"

change name of function call to something else may callFun.
<a onclick='javascript:callFun(\"" + mail +"\");'>mail</a>
or alternate is
<a emailId='" + mail +"'>mail</a>
$('#applicantstbl').on('click','.btn-small',function(e){
e.preventDefault();
callFun($(this).attr('emailId'));
});

Related

hyperlink on update button (ajax json)

It's my first time using json and I'm trying to make an update button on a table that i make with ajax json, there is a problem that i can't put id_news attribute on the tag along with the target link. I tried put it next to the target link, but it doesn't work, and even the tables doesn't show anything, is there any way to make it work?
$(document).ready(function() {
display_data_info();
function display_data_info() {
$.ajax({
type: 'ajax',
url: '<?php echo base_url()?>/information/data_read_info',
async: false,
dataType: 'json',
success: function(data) {
var html = '';
var i;
var no;
var id_news;
for (i = 0; i < data.length; i++) {
no = +1;
html += '<tr>' +
'<td>' +
no +
'</td>' +
'<td>' +
data[i].news_title +
'</td>' +
'<td>' +
data[i].news_info +
'</td>' +
'<td>' +
data[i].news_status +
'</td>' +
'<td><a href="<?php echo site_url("information/display_update_info/".data[i].id_news); ?>" class="btn btn-app">' +
'<i class="fas fa-edit"></i> ' +
'</a>' +
'</td>' +
'</tr>';
}
$('#show_data_info').html(html);
}
});
}
});
[wanted to post just a comment, but haven't enough reputation yet. Perhaps a moderator can change my feedback into a comment?]
I see multiple typos and mistakes here:
In the first php part, put a ; after base_url()
You are not initializing no before you do no += 1
Instead of no += 1 you do no = +1 (which may accidentally overcome the previous error but it's probably not what you want)
In the <td><a href=.... line you are mixing up single and double quotes
In that same line, your javascript variable is inside PHP. data[i].id_news does not exist in PHP scope.
Check your web console and PHP error log, there will be several errors.

jquery onchange function is not calling

i have the following piece of code:
function teamAuswaehlen() {
$.post("Auswahl_Abteilung?_=" + new Date().getTime(), function(data) {
eintraege = "<div class='col-md-12 col-xs-12'>" +
"<div class='form-group'>" +
"<select class='form-control' id='teams' title='Wählen Sie hier ihre Teamansicht'>"
if (data.length > 1) {
$("#kalenderAuswahl .modal-body").empty();
$.each(JSON.parse(data), function(key, value) {
eintraege += "<option id='" + value.Team_ID + "'>" + value.TE_Kurzbezeichnung + "| " + value.TE_Langbezeichnung + "</option>";
});
eintraege += "</select>" +
"</div>" +
"</div>";
}
if (data.length > 1) {
$("#kalenderAuswahl .modal-body").append(eintraege);
$("#kalenderAuswahl").modal("show");
}
}).done(function() {
$("#teams").change(function() {
getId(this);
});
});
}
The Modal is build dynamicly at the start of the programm.
So the onchange event i want to call if a user change the select box is store in the done block.
But if i trie the code, nothing happens so the onchange event is not fired.
So how can i handle that ?
Here is code snippet for your change event.
$('body').on('change', '#teams', function(e) {
e.preventDefault();
// do your stuff
});
You can write this change event code in below section
Before body tag end Or
You can write in $(document).ready(function() {})
you can remove done method and paste your code to body.
select event with body tag as like $('body').on('change', '#teams'
or
just use like this $('body').on('change', '#teams' in done method.
No need to place code in done().place the following code anywhere in tag
$(document).on('change','#teams',function() {
getId(this);
});

Dynamically added code not responding to jQuery click

I have read several questions on this forum about this problem, but it still not work for me. All other buttons and clickable elements that are in the code from the beginning works fine, but not those element that is passed dynamically. Everything works when I run the page local, but online it's not working. What could be wrong?
This is part of the dynamically code: (The data[i].id comes from an Ajax request)
html += "<td width='20px'>" + status + "</td><td class='updateCompleted' data-id='" + data[i].id + "'>" + data[i].text + "</td><td align='right' width='20px'><img src='icons/icon-remove.png' alt='remove icon' class='removeIcon' data-id='" + data[i].id + "'></td>";
I then add the code like this:
$(".contentList table").html(html);
And this is the jQuery to detect the click:
// Handle click to set row in list to completed
$(document).on("click",".updateCompleted", function(e){
e.preventDefault();
var id = $(this).data("id");
updateData(id,1)
console.log("Test");
});

function called on page load while it must be called on onclick only

Here I want to call updateRecord("+n+") function on click Update button
here res.data is the response from ajax. But when the page loads the updareRecord called itself. Following code is written in js file. and on click getting following error:
Uncaught SyntaxError: Unexpected identifier.
I request to mention exact point if you don't understand any point of question instead mark it negative.
$.map(res.data,function(n,i){
if (n['type'] == 1)
html += "<tr><td>"
+ n['locationName']
+ "</td><td>"
+ n['categoryName']
+ "</td><td>"
+ n['day']
+ "</td><td>"
+ n['status']
+ "</td><td><input type='button' onclick = '"+updateRecord(n)+ "' value='Update'/></td></tr>";
});
Because you are calling the function already when callback function is called.
This happens right here on this line:
+ "</td><td><input type='button' onclick = '"+updateRecord(n)+ "' value='Update'/></td></tr>";
You call first updateRecord(n) and then append the return value to the text.
I would avoid adding events to DOM directly, but rather use something like this:
var button = $('<input type="button" value="Update" />');
button.click(function(event) {
updateRecord(n);
}
The problem is, that you call the method:
html += "<input type='button' onclick = '"+updateRecord(n)+"' ...";
/* like this you execute the method directly,
like any other function call in javascript */
In case you'll write it like this:
html += "<input type='button' onclick = 'updateRecord("+n+")'...";
/* like this it is a string, and will be
interpreted by the javascript click eventhandler
after adding the html string to the DOM */
It could work as expected, but the problem is, that you'll want to set an array/ object as parameter, which will cause an javascript error. To avoid that you could also do something like this:
$.map(res.data,function(n,i){
if (n['type'] == 1) {
html += "<tr><td>" + n['locationName'] + "</td><td>" +
n['categoryName'] + "</td><td>" + n['day'] + "</td><td>" +
n['status'] + "</td><td>" +
"<input class='update-button' data-value='"+
/* since n is an associative array, will need
to stringify in a special way */
JSON.stringify(n).replace(/'/g, "\\'")
+"' type='button' value='Update'/></td></tr>";
}
});
/* bind an click event to all .update-button elements,
whenever these elements will be appended to the DOM */
$(document).on('click','.update-button',function() {
updateRecord($(this).data('value'));
});

How to pass a specific object to a function through an html link?

Currently I am working on a site where I receive a list of objects from a data base and I am listing them in a pop-up table. I'd like one column of the table to list the object id and another to list links which call a function for that specific object. My issue is that I do not know how to do this when appending this data to a table.
Any ideas?
var tableContent ="<tr>";
for( var i =0; i<results.length ; i++)
{
tableContent += "<td>" + results[i].get("id") + "</td>"
tableContent += "<td>" + "<a>Open ID Contents</a>" + "</td>"
//I want this link to pass results[i] to a function^
}
tableContent += "</tr>"
$("#List").append(tableContent)
You can construct your a items in this way:
var $a = $('<a class="hasPopupData">...</a>');
$a.data('popup', { /*Your data goes here */ });
$a.appendTo($parent);
And then handle clicks using code like this:
$parentTable.on('click', 'a.hasPopupData', function(){
var $a = $(this),
data = $a.data('popup');
createPopup(data);
return false;
});
Note that jQuery attaches data to DOM node in ‘native’ presentation, without converting them to JSON first.
There are a variety of ways. A simple way is to pass the variable as JSON.
var js = "afunction('" + JSON.stringify(results[i]) + "');return false;"
tableContent += "<td>" + '<a onclick="' + js + '">Open ID Contents</a>' + "</td>"

Categories

Resources