I have an AJAX post that returns a data set. this part works completely fine.
However when building the table in the success area of the AJAX GET i create a Checkbox for each row.
When i then carry out an "On Click" Event of the checkbox it doesn't work.
Here is the AJAX/Table creation
function ListAppointments() {
$.ajax({
type: "GET",
url: "../Appointments",
data: { 'id': id },
contentType: "application/json; charset=UTF-8",
dataType: "json",
success: function (response) {
if (response.length > 0) {
$.each(response, function (i, item) {
var apptDate, apptTime, arrivalTime = "";
if (item.ApptDateTime != null) {
apptDate = moment(item.ApptDateTime).format('DD-MMM-YYYY');
apptTime = moment(item.ApptDateTime).format('HH:mm');
}
var row = '<tr class="grid__row--select"' + item.ID + '">' +
'<td><input id="check" name="check" id="chk" class="chkBoxOPA" type="checkbox" value="' + item.ID + '"/></td>' +
'<td style = "white-space:nowrap;">' +
'<div class="media-left">' +
'</div>' +
'<div class="media-body">' +
'<h3 class="list-group-item-heading">' + item.DisplayName + '</h3>' +
'<span class="list-group-item-text">' + item.DisplayDOB + ' (' + item.DisplayAge + ')</span>' +
'</div>' +
'</td>' +
'<td class="text-center" style="white-space:nowrap;">' +
'<span class="list-group-item-heading">' + apptDate + '</span>' +
'<span class="list-group-item-text">' + apptTime + '</span>' +
'</td>' +
'<td>' +
'<span class="grid__row--smaller-text">' + item.OutcomeDesc + '</span>' +
'</td>' +
'<td class="text-center" style="white-space:nowrap;">' +
'<span class="grid__row--smaller-text">' + arrivalTime + '</span>' +
'</td>' +
'</tr>';
$('#appointments-body').append(row);
});
}
else {
console.log(JSON.stringify(response));
}
},
error: function (response) {
console.log(JSON.stringify(response));
}
});
}
When i then try to do this
$(".chkBoxOPA").on("change", ":checkbox", function () {
alert('test');
});
It doesnt seem to bind or work.
The ListAppointments function is run on a button click event.
You added rows dynamically so use document
$(document).on("change", ".chkBoxOPA", function () {
alert('anything');
});
OR if you dont want to use class then use as
$(document).on("change", "input[type=checkbox]", function () {
alert('anything');
});
.chkBoxOPA and :checkbox refers to the same element but with your selector you are looking for :checkbox inside .chkBoxOPA and the selector fails to target the check box. You can find the element .chkBoxOPA inside tr.
Please Note: The attribute id must be unique in document.
Try:
$("tr").on("change", ".chkBoxOPA", function () {
alert('test');
});
Demo:
var checkbox = `<td><input name="check" class="chkBoxOPA" type="checkbox" value="item1"/></td>`;
$('tbody tr').append(checkbox); //add check box dynamically
$("tr").on("change", ".chkBoxOPA", function () {
alert('The index is: ' + $(".chkBoxOPA").index(this));
});
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table style="width:100%">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Check</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jill</td>
<td>Smith</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
</tr>
</tbody>
</table>
Ajax is Asynchronous And when you write This Code
$(".chkBoxOPA").on("change", ":checkbox", function () {
alert('test');
});
that checkbox didn't add to table Then you have to solution first
$.ajax({
.....
async:false,
.....
})
or you can use this solution
......
$('#appointments-body').append(row);
$(".chkBoxOPA").on("change", ":checkbox", function () {
alert('test');
});
.......
Related
Problem
Hi all, I am trying to refresh my table data on a set interval of 10 seconds... problem is that when I initially load the page there is a delay of 10 seconds before my table is shown...
Code
markup
<h2>Employee List</h2>
<!-- table -->
<table class="table table-striped table-hover table-responsive">
<thead>
<tr>
<td>ID</td>
<td>Emplyee Name</td>
<td>Address</td>
<td>Created at</td>
<td>Action</td>
</tr>
</thead>
<!-- table content dynamically generated by the javascript -->
<tbody id="showdata"></tbody>
<!-- end content -->
</table>
<!-- end table -->
jQuery
$(function(){
pollServer();
function pollServer(){
window.setTimeout(function () {
alert('hey');
$.ajax({ // this is a json object inside the function
type: 'ajax',
url: '<?php echo base_url('employee/showAllEmployee'); ?>',
async: false,
dataType: 'json',
success: function(data){
console.log(data);
var html = '';
var i;
for(i = 0; i < data.length; i++){
html += '<tr>' +
'<td>' + data[i].employee_id + '</td>' +
'<td>' + data[i].employee_name + '</td>' +
'<td>' + data[i].address + '</td>' +
'<td>' + data[i].created_at + '</td>' +
'<td>' +
'<div class="pull-right">' +
'<a class="btn btn-info btn-xs item-edit" href="javascript:;" data="' + data[i].employee_id + '">Edit</a>' +
'<a class="btn btn-danger btn-xs item-delete" href="javascript:;" data="' + data[i].employee_id + '"><i class="fa fa-times"></i></a>' +
'</div>' +
'</td>' +
'</tr>'
}
$('#showdata').html(html);
},
error: function(){
alert('Could not get Data from Database');
},
complete: function(){
pollServer();
}
})
}, 10000);
}
});
Question
How do I get my data on page load, and then ping the server every 10 seconds thereafter?
change pollServer as follows
function pollServer(){
$.ajax({ // this is a json object inside the function
// removed for clarity
complete: function(){
setTimeout(pollServer, 10000);
}
});
}
Just call the same function inside it's success callback with a timeout.
function pollServer() {
$.ajax({
...
success: function(data) {
setTimeout(function() {
pollServer();
},10000);
}
});
}
// Call the function on load
pollServer();
I'm very green when using jquery and AJAX. Not sure if AJAX would help in this situation. I've looked at this question its the closest to what i'm looking for.
Add new row to table using jQuery on enter key button
var inp = $("#txt");
// where #txt is the id of the textbox
$(".table-cell-text").keyup(function (event) {
if (event.keyCode == 13) {
if (inp.val().length > 0) {
$('#myTable tr:last').replaceWith('<tr class="table-row"><td class="table-cell">' + inp.val() + '</td>' +
'<td class="table-cell">' +
'<td></td>' +
'</td>' +
'<td class="table-cell">' +
'</td></tr>');
}
}
});
FIDDLE
I have a MySQL DB that I would like data retrieved from based off of the sku # entered into their respective rows. I have this working with a submit button using PHP, but this is for a project I have that uses a Barcode scanner.
There is a second part to this question but i'll try to figure that out on my own first before asking.
<?
if (!empty($_POST))
{
$db = new mysqli('localhost', 'root', 'password', 'table');
$result = $db->query('SELECT * FROM `users` ');
$result = $result->fetch_array();
print($result['id'].' - '.$result['username'] .' - '.$result['password']);
die();
}
?>
<!DOCTYPE html>
<html>
<head>
<!-- head here -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.2/modernizr.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div><input id="txt" placeholder="Enter barcode" type="text"></div>
<table id="myTable">
<tr class="table-header">
<td class="table-cell">SKU</td>
<td class="table-cell">MODEL </td>
<td class="table-cell">DESCRIPTION</td>
<td class="table-cell">QTY</td>
</tr>
<tr class="table-row">
</tr>
</table>
<script>
var inp = $("#txt");
// where #txt is the id of the textbox
$("#txt").keyup(function (event) {
if (event.keyCode == 13)
{
if (inp.val().length > 0)
{
$.ajax({
url: "test.php",
type: "post", //send it through POST method
data: {id: inp.val()},
success: function(response)
{
values = response.split(' - ');
$('#myTable tr:last').replaceWith('<tr class="table-row"><td class="table-cell">' + inp.val() + '</td>' +
'<td class="table-cell">' + values[0] +
'<td> ' + values[1] + '</td>' +
'</td>' +
'<td class="table-cell">' + values[2] +
'</td></tr>');
}});
}
}
});
</script>
</body>
</body>
</html>
I tried with my dummy database with users and I get:
SKU MODEL DESCRIPTION QTY
40 1 Username 9z600248b669b62d75b300a07b89060n
I had limited success with the edited code. When I try to enter a different item # into the input field only the first value updates. Also, I'm trying to add a new row and retain the last row after entering a new value in the input field.
Here is the latest version of the script:
<script>
var inp = $("#txt");
// where #txt is the id of the textbox
$("#txt").keyup(function (event) {
if (event.keyCode == 13)
{
if (inp.val().length > 0)
{
$.ajax({
url: "index.php",
type: "POST", //send it through POST method
data: {id: inp.val()},
success: function(response)
{
values = response.split(' - ');
$('#report tr:last').replaceWith(
"<tr class='table-row'><td class=''>" + inp.val() + "</td>" +
"<td class=''>" + values[1] + "</td>" +
"<td class=''>" + values[2] + "</td>" +
"<td class=''>" + values[3] + "</td></tr>");
}});
}
}
}});
</script>
I did some more diggin around and I was able to resolve some of the issues I was having. However, I still can't get data from the DB when a new row is added.
Below is my code:
<div class="row">
<div class="col-md-1"></div>
<div class="col-xs-3">
<h3 class="h4 text-center"><input type="text" name="barcode" id="txt" size="90" class="col-md-9" value="" placeholder="Barcode / Product Name"></h3>
</div>
</div>
<br />
<div class="row">
<div class="col-md-1"><p class=""></p></div>
<div class="col-md-6">
<table id="report" class="table table-bordered table-hover">
<thead>
<tr>
<td>SKU</td>
<td>Model</td>
<td>Item Description</td>
<td>Qty</td>
</tr>
</thead>
<tbody>
<tr class='table-row'>
</tr>
</tbody>
</table>
</div>
</div>
<script>
var inp = $("#txt");
// where #txt is the id of the textbox
$("#txt").keyup(function (event) {
if (event.keyCode == 13)
{
if (inp.val().length > 0)
{
$.ajax({
url: "index.php",
type: "POST", //send it through POST method
data: {id: inp.val()},
success: function(response)
{
values = response.split(' - ');
$('#report tr:last').after(
"<tr class='table-row'><td class=''>" + inp.val() + " </td>" +
"<td class=''>" + values[1] + "</td>" +
"<td class=''>" + values[2] + "</td>" +
"<td class=''>" + values[3] + "</td></tr>");
}});
}
$('input[name=barcode]').val('');
}
});
</script>
I am new in Bootstrap JS. I have a table made with Bootsrap JS, whose data came from a Json file. Here is The Code-
<div class="container-fluid">
<div class="row">
<div class="col-md-8">
<div class="fixedscroll">
<table id="user_table" class="table table-hover table-bordered table-striped responsive" style="margin-bottom: 0;" class="display">
<thead>
<tr>
<th>UID</th>
<th>Name</th>
<th>Address</th>
<th>Tags</th>
<th>Edit tags</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
function showAll(){
$.ajax({
url: "showAll",
dataType:"json",
success:function(data){
$('#user_table tr:gt(0)').remove();
jQuery.each(data['Payload'], function(index, value) {
var row = '<tr>'
+ '<td id="tduid">'+ value['uid']+ '</td>'
+ '<td>'+ value['name']+ '</td>'
+ '<td>'+ value['address']+ '</td>'
+ '<td>'+ value['tag1']+ ',' + value['tag2']+ ',' + value['tag3']+'</td>' + '<td>'+ '<button class="deleteUser btn btn-danger" type="submit">Edit</button>' + '</td></tr>';
$('#user_table').append(row);
});
}
});
Now This Payload is the name of my json, which came from a servlet where I call the database.
Now let, there is 3 tags. But some of rows have 2 tags. So, when I put the values in json the Json looks like-
{"Payload":[{"uid":"u01","name":"Subho","address":"Dumdum","tag1":"aircel","tag2":"vodafone","tag3":"airtel"},{"uid":"u02","name":"Jeet","address":"Baruipur","tag1":"airtel","tag2":"","tag3":"aircel"},{"uid":"u03","name":"Diba","address":"Jadavpur","tag1":"vodafone","tag2":"aircel","tag3":"airtel"},{"uid":"u04","name":"Tommy","address":"Baguihati","tag1":"aircel","tag2":"vodafone","tag3":""},{"uid":"u05","name":"Jonty","address":"Rahara","tag1":"","tag2":"vodafone","tag3":"airtel"},{"uid":"u06","name":"Gourav","address":"Tripura","tag1":"aircel","tag2":"vodafone","tag3":"airtel"}]}
Now You can see, that for UID=U02 there is 2 tags. And the output looks like picture attached. How can I remove the blank values or null values???? Please anyone help me...
I think, you are saying about the extra , in the tags column... one messy solution is
$.ajax({
url: "showAll",
dataType: "json",
success: function (data) {
$('#user_table tr:gt(0)').remove();
jQuery.each(data['Payload'], function (index, value) {
var tags = $.map([value.tag1, value.tag2, value.tag3], function (value) {
return value || undefined;
});
var row = '<tr>' + '<td id="tduid">' + value['uid'] + '</td>' + '<td>' + value['name'] + '</td>' + '<td>' + value['address'] + '</td>' + '<td>' + tags + '</td>' + '<td>' + '<button class="deleteUser btn btn-danger" type="submit">Edit</button>' + '</td></tr>';
$('#user_table').append(row);
});
}
});
As #Alnitak said
var tags = [value.tag1, value.tag2, value.tag3].filter(function (value) {
return value !== undefined;
});
console.log(tags)
I'm trying to create a single-page app that pulls information from a JSON file, displays it on the screen, and perform a few actions.
Right now, I have all of the information being displayed on the screen properly: http://jsfiddle.net/rcsayf7t/3/
I need the "Remove" button to asynchronously remove the JSON object from the screen when it's clicked, but unfortunately have no idea how to go about accomplishing it.
HTML:
<table>
<thead>
<tr>
<th scope="col"></th>
<th scope="col">Name</th>
<th scope="col">Message</th>
<th scope="col">Date</th>
<th scope="col"></th>
</tr>
</thead>
<tbody class="tweets-result"></tbody>
</table>
jQuery:
// helper function for formatting date
function formatDate(date) {
var dateSplit = date.split(" ");
var displayDate = dateSplit[0] + ", " + dateSplit[1] + " " + dateSplit[2];
// return the result
return displayDate;
}
$(document).ready(function () {
// start ajax request
$.ajax({
url: "https://gist.githubusercontent.com/arlodesign/7d80edb6e801e92c977a/raw/24605c9e5de897f7877b9ab72af13e5b5a2e25eb/tweets.json",
dataType: "text",
success: function (data) {
// store the JSON data
var tweetData = $.parseJSON(data);
// loop through json values and build the table
$.each(tweetData.tweets, function (index, item) {
$('.tweets-result').append(
'<tr>' +
'<td><img src="' + item.profile_image_url + '" alt="#' + item.screen_name + ' avatar"></td>' +
'<td>#' + item.screen_name + '</td>' +
'<td>' + item.text + '</td>' +
'<td>' + formatDate(item.created_at) + '</td>' +
'<td>Remove</td>' +
'</tr>');
// WHEN YOU CLICK "REMOVE", THE TWEET SHOULD
// ASYNCHRONOUSLY BE REMOVED FROM THE SCREEN
});
}
});
});
Live demo
Just add the following inside ajax success:
$('.remove_row').click(function(){
$(this).closest('tr').remove();
});
and the following code as remove attribute:
class="remove_row"
Full JS (read my comments):
// helper function for formatting date
function formatDate(date) {
var dateSplit = date.split(" ");
var displayDate = dateSplit[0] + ", " + dateSplit[1] + " " + dateSplit[2];
// return the result
return displayDate;
}
$(document).ready(function () {
// start ajax request
$.ajax({
url: "https://gist.githubusercontent.com/arlodesign/7d80edb6e801e92c977a/raw/24605c9e5de897f7877b9ab72af13e5b5a2e25eb/tweets.json",
dataType: "text",
success: function (data) {
// store the JSON data
var tweetData = $.parseJSON(data);
// loop through json values and build the table
$.each(tweetData.tweets, function (index, item) {
$('.tweets-result').append(
'<tr>' +
'<td><img src="' + item.profile_image_url + '" alt="#' + item.screen_name + ' avatar"></td>' +
'<td>#' + item.screen_name + '</td>' +
'<td>' + item.text + '</td>' +
'<td>' + formatDate(item.created_at) + '</td>' +
'<td class="remove_row">Remove</td>' + // ## Here add the class remove_row
'</tr>');
// WHEN YOU CLICK "REMOVE", THE TWEET SHOULD
// ASYNCHRONOUSLY BE REMOVED FROM THE SCREEN
});
//## Here assign the even on click for the remove button
$('.remove_row').click(function(){
$(this).closest('tr').remove();
});
}
});
});
I'm creating a 'live' leaderboard table. Every X seconds, an AJAX request is sent to the server to load the latest leaderboard data.
If there's a change in data, the leaderboard will instantly update upon the AJAX request.
However - If there IS a change, instead of instantly showing the new data, I want to animate the table row to its new position instead of instantly reloading it. What is the best way of achieving something like this?
I'm updating the leaderboard at the moment like so:
$(document).ready(function() {
showLeaderboard();
if (autoUpdate != false) {
window.setInterval(function(){
$('#wrapper h2, #leaderboard tbody tr').remove(updateLeaderboard());
}, reloadInterval);
}
});
function updateLeaderboard() {
leaderBoardType;
numRecords;
quizIDs;
topListTitle;
latestTitle;
$.webMethod({
url: 'xxx',
data: '{quizIDs:"'+quizIDs+'",numRecords:"'+numRecords+'"}',
type: 'POST',
cache: false,
beforeSend: function () {
$('body').append('<div class="loading"></div>');
},
success: function (ret)
{
$('.loading').remove();
$('#wrapper').prepend(topListTitle);
$.each(ret.leaderboard,function(i){
pos = i + 1;
str = '<td class="position">' + pos + '</td>';
str += '<td class="name">' + ret.leaderboard[i].first_name + ' ' + ret.leaderboard[i].last_name + '</td>';
str += '<td class="time">' + getTime(ret.leaderboard[i].time_taken) + '</td>';
str += '<td class="points">' + ret.leaderboard[i].points + '</td>';
//str += '<td>' + ret.leaderboard[i].last_name + '</td>';
//str += '<td>' + ret.leaderboard[i].incorrect_attempts + '</td>';
//str += '<td>' + ret.leaderboard[i].user_id + '</td>';
$('#leaderboard tbody').append('<tr>'+str+'</tr>');
});
},
error: function (response) { alert(response.responseText); }
});
}
HTML
<table id="leaderboard">
<thead>
<tr>
<th class="position">Position</th>
<th class="name">Name</th>
<th class="time">Time Taken</th>
<th class="points">Points</th>
</tr>
</thead>
<tbody>
</tbody>
</table>