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");
});
Related
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.
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'));
});
I fetched the data from remote sever, and appended different rows to the table, now, I want to get all the checked box data and do further treatment, like when tick the box, then the data will be pushed to an array, and remove the element from that array when tick off the check box. so now, the question is, i can not select the checked box which the attribute was changed after appending work, the core code part is:
$row.find('input[ischecked="unchecked"]').on('click', function(){
$(this).attr('ischecked','checked'); // it works here
if($.inArray(this.value, tickedArray) === -1){
tickedArray.push(this.value);
}
console.log('checked');
});
// it can not get the ischecked="checked"
$row.find('input[ischecked="checked"]').on('click', function(){
console.log('unchecked');
});
and the full code here:
$(function(){
var url = some url;
var tickedArray = [];
$.ajax({
url: url,
type:'GET',
xhrFields: {
withCredentials: true,
},
success:function(data){
$.each(data.stories, function(index, value){
var $row = $("<tr>" +
"<td><input type='checkbox' value="+ value.id +" ischecked='unchecked'></td>" +
"<td>" + value.title + "</td>"+
"<td>" + value.author_name + "</td>"+
"<td>" + value.likes + "</td>"+
"<td>" + value.created + "</td>"+
"</tr>");
$row.find('input[ischecked="unchecked"]').on('click', function(){
$(this).attr('ischecked','checked');
if($.inArray(this.value, tickedArray) === -1){
tickedArray.push(this.value);
}
console.log('checked');
});
$row.find('input[ischecked="checked"]').on('click', function(){
console.log('unchecked');
});
$('#stories_list_table > tbody:last').
append($row);
});
}
});
});
$row.find('input[ischecked="checked"]').on('click', function(){
console.log('unchecked');
});
This selector won't find any checkbox because there aren't any at that moment. Instead of creating 2 click events you should only create 1 change event and check the ischecked attribute for it's value.
Also, why do you create your own ischecked attribute instead of using the standard checked property?
I think you can try using event delegation, like this :
$row.on('click', 'input[ischecked="checked"]', function(){
console.log('unchecked');
});
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'));
});
I updated jquery so i could play with the new jquery mobile ui 1.3 and for some reason my form no longer update page any more, it worked previously but it wasn't through ajax, it simply submitted the form without ajax, I would however like ajax to just fetch the new data and append it to the div instead of reloading the whole page again when the popup closes.
I use a popup module for the form and on submission it should append the new information to #content ul
The JS.
<!-- Load Json data and events -->
<script type="text/javascript">
jQuery('#new_rave').live('submit',function( event ) {
$.ajax({
url: 'http://whoops/goodtimes',
type: 'POST',
dataType: 'json',
data: $('#new_rave').serialize(),
success: function( data ) {
for( var id in data ) {
jQuery('#').html(data[id]);
}
}
});
return false;
});
$(document).ready(function() {
$.getJSON('http://whoops/goodtimes', function( goodtimes ) {
$.each(goodtimes, function( goodtime ) {
var output =
"<li><a href="+this.goodtime.id+">" +
"<h3>" + this.goodtime.title + "</h3>" +
"<p>" + this.goodtime.post + "</p>" +
"<p class='ui-li-aside'><strong>" +
this.goodtime.created_at + "</strong></p>" +
"</a></li>";
$('#content ul').append(output).listview('refresh');
});
});
});
</script>
The form
<!-- New item Popup -->
<div data-role="popup" class="ui-content"
data-overlay-theme="a" data-position-to="window" id="add">
<form id="new_rave">
<label for="goodtime_title">Title</label>
<input type="text" name="goodtime[title]" id="goodtime_title">
<label for="goodtime_post">Rave</label>
<div data-role="fieldcontain">
<textarea name="goodtime[post]" id="goodtime_post"></textarea>
</div>
<input type="submit" value="submit">
</form>
</div>
and the content div
<div id="content" data-role="content">
<ul data-role="listview" data-theme="d" data-divider-theme="d"></ul>
</div><!-- /content -->
Intro
Your problem is probably due to $(document).ready(function(){. In jQuery Mobile, Ajax is used to load the content of each page into the DOM as you navigate. Because of this $(document).ready() will trigger before your first page is loaded and every code intended for page manipulation will be executed after a page refresh.
Everything here can be found described with more details in my personal blog article.
In case this is not a problem, use Firefox/Chrome plugin Firebug to test if ajax call has reached a server and if response has been received.
Last thing, don't refresh listview every time you append a new element. listview refresh is a huge time sink, every refresh can last around 50ms but do it numerous time and your restyling could go forever.
Solution
So change this:
$.getJSON('http://whoops/goodtimes', function(goodtimes) {
$.each(goodtimes, function(goodtime) {
var output =
"<li><a href="+this.goodtime.id+">" +
"<h3>" + this.goodtime.title + "</h3>" +
"<p>" + this.goodtime.post + "</p>" +
"<p class='ui-li-aside'><strong>" + this.goodtime.created_at + "</strong></p>" +
"</a></li>";
$('#content ul').append(output).listview('refresh');
});
});
to this:
$.getJSON('http://whoops/goodtimes', function(goodtimes) {
$.each(goodtimes, function(goodtime) {
var output =
"<li><a href="+this.goodtime.id+">" +
"<h3>" + this.goodtime.title + "</h3>" +
"<p>" + this.goodtime.post + "</p>" +
"<p class='ui-li-aside'><strong>" + this.goodtime.created_at + "</strong></p>" +
"</a></li>";
$('#content ul').append(output);
});
$('#content ul').listview('refresh');
});
EDIT
Your problem with constant post repeating comes to how jQuery Mobile handles event binding. Because pages are constantly revisited each time events are going to be bound over and over. In your case that would be an event that executes JSON call.
This can be prevented in several ways, most common one is to unbind event before binding it. For example:
$('#test-button').off('click').on('click', function(e) {
alert('Button click');
});