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>
Related
I've a litte problem diplaying a table correctly.
The table-header ist not consistent with the table-body.
The table date gets displayed in the colums 1/3/5/7, so the odd columns are getting skipped, idk why this happens.
On the following link you can look how the table gets displayed.
Relevant Code:
HTML-Code:
<div id="accreqlist" hidden="true">
<h1>Accountanfragen Liste</h1>
<button class="btn btn-secondary btn-lm" id="accreqreturnbtn">zurück</button>
<form id="accreqlist_form">
<div id=accreq_message class="form__message form__message--error"></div>
</form>
<table class="tablelist" id="tblAccList">
<thead>
<tr>
<th>Accountanfrage ID</th>
<th>Name</th>
<th>E-Mail</th>
<th>Mobile</th>
<th>Action 1</th>
<th>Action 2</th>
</tr>
</thead>
<tbody>
<!--will get filled through js file-->
</tbody>
</table>
</div>
JS-Code:
function accountRequestlistclicked() {
$.getJSON("/api/accountRequests").done(handleAccountRequestlistReply);
}
function handleAccountRequestlistReply(reqs) {
$("#tblAccList tbody").empty();
for (let req of reqs) {
addReqToList(req);
}
}
function addReqToList(req) {
let id = req["accountRequestId"];
var newRow = "<tr>";
newRow += "<td>" + req["accountRequestId"] + "<td>";
newRow += "<td>" + req["accountRequestName"] + "<td>";
newRow += "<td>" + req["accountRequestEmail"] + "<td>";
newRow += "<td>" + req["accountRequestMobile"] + "<td>";
newRow +=
"<td> <button id = 'u" +
req["accountRequestId"] +
"' onClick='deleteAccRequest(" +
req["accountRequestId"] +
")'> Delete </button> </td>";
newRow +=
"<td> <button id = 'u" +
req["accountRequestId"] +
"' onClick='createUser(" +
req["accountRequestId"] +
")'> Account erstellen </button> </td>";
newRow += "</tr>";
$("#tblAccList tbody").append(newRow);
}
//accreq löschen
function deleteAccRequest(id) {
var urlstring = "/api/deleteAccountRequest/" + id;
$.ajax({
type: "DELETE",
url: urlstring,
success: deleteReqRespons,
dataType: "json",
contentType: "application/json",
});
}
//user erstellen
function createUser(id) {
var urlstring = "api/createUser/" + id;
$.ajax({
type: "Post",
url: urlstring,
success: createUserResponse,
dataType: "json",
contentType: "application/jsin",
});
}
Does somebody know how i can fix the table, so that the colums gets displayed correctly?
Im very thankful of every input!
Uff i know what was wrong. I forgot to close the td-tags. so for each data the </th> was missing :(( sorry for stealing your time, with this simple problem.
cheers
1.This is my code for my HTML table where I'm unable to display the data from it using my javascript code below.
<table id="empTable">
<tr>
<th>Type</th>
<th>SimiScore</th>
<th>Rank</th>
<th>Introversion/Extraversion</th>
<th>Intuitive/Observant</th>
<th>Thinking/Feeling</th>
<th>Judging/Perceiving</th>
</tr>
{% for doc in docs %}
<tr>
<td>{{doc["type"]}}</td>
<td>{{doc["Simiscore"]}}</td>
<td>{{doc["Rank"]}}</td>
<td>{{doc["Introversion/Extraversion"]}}</td>
<td>{{doc["Intuitive/Observant"]}}</td>
<td>{{doc["Thinking/Feeling"]}}</td>
<td>{{doc["Judging/Perceiving"]}}</td>
</tr>
{% endfor %}
</table>
<p><input type="button" id="bt" value="Show Table Data" onclick="showTableData()" /></p>
<p id="info"></p>
2.This is my javascript code to display the data, but I'm unable to display it
<script>
function showTableData() {
document.getElementById('info').innerHTML = "";
var myTab = document.getElementById('empTable');
// LOOP THROUGH EACH ROW OF THE TABLE AFTER HEADER.
for (i = 1; i < myTab.rows.length; i++) {
// GET THE CELLS COLLECTION OF THE CURRENT ROW.
var objCells = myTab.rows.item(i).cells;
// LOOP THROUGH EACH CELL OF THE CURENT ROW TO READ CELL VALUES.
for (var j = 0; j < objCells.length; j++) {
info.innerHTML = info.innerHTML + ' ' + objCells.item(j).innerHTML;
}
info.innerHTML = info.innerHTML + '<br />'; // ADD A BREAK (TAG).
}
}
</script>
{
$(document).ready(function()
{
$.ajax({
url: "getjson.php",
type: "POST",
dataType:"json",
success: function (response)
{
var trHTML = '';
$.each(response, function (key,value) {
trHTML +=
'<tr><td>' + value.id +
'</td><td>' + value.konu +
'</td><td>' + value.aciklama +
'</td><td>' + value.giris_tarih +
'</td><td>' + value.degistirilme_tarih +
'</td><td>' + value.ad_soyad +
'</td><td>' + value.email +
'</td></tr>';
});
$('#records_table').append(trHTML);
}
});
});
}
this is an example you can use
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');
});
.......
I have a table that is programmatically added with an onclick event that calls a specific javascript function with the id of the row I want to edit. However it is not called. I have tried changing the button by adding a class and trying to get something there but it does not work. This used to work and I cannot figure out why or how to fix it.
function buildTable() {
$.ajax({
url: "getTable.php",
dataType: "json",
success: function(result) {
if (result != null) {
$('#measurements tbody tr').remove();
result.forEach(function (measurement) {
var message = "<tr><td>" + dateFromtimestamp(measurement.weigh_date) + "</td>";;
message += "<td>" + measurement.weight + "</td>";
message += "<td><input type='hidden' value='" + measurement.id + "'>" + measurement.waist + "</td>";
message += "<td>" + measurement.upperBp + "</td>";
message += "<td>" + measurement.lowerBp + "</td>";
message += "<td>" + measurement.comment + "</td>";
message += "<td><button type='button' class='btn btn-outline-warning' onlick='editRow(" + measurement.id + ")'>";
message += "<span class='glyphicon glyphicon-pencil'></span></button> ";
message += "<button type='button' class='btn btn-outline-danger' onlick='removeRow(" + measurement.id + ")'>";
message += "<span class='glyphicon glyphicon-remove'></span></button></td></tr>";
$('#measurements').append(message);
});
}
}
});
}
The following is the HTML table it is being added to:
<div class="panel panel-info">
<div class="panel-heading text-center">Past measurements</div>
<div class="panel-body">
<table class="table table-striped" id="measurements">
<thead class="thead-dark">
<th scope="col">Date</th>
<th scope="col">Weight</th>
<th scope="col">Waist</th>
<th scope="col">Systolic (Upper)</th>
<th scope="col">Diastolic (Lower)</th>
<th scope="col">Comment</th>
<th scope="col">Action</th>
</thead>
<tbody>
</tbody>
</table>
<div class="row"> </div>
</div>
</div>
This is the edit function in question just in case I miss something with the argument signature:
function editRow(id) {
$.ajax({
url: "getMeasurement.php",
type: "post",
dataType: "json",
data: {
"id": id
},
success: function(data) {
if (data != null) {
data.forEach(function(result){
var id = result.id;
$('#editMeasurement').modal('show');
$('#editupper').val(result.upperBp);
$('#editlower').val(result.lowerBp);
$('#editwaist').val(result.waist);
$('#editweight').val(result.weight);
$('#editcomment').text(result.comment);
$('#editRowHidden').val(id);
});
}
}
});
}
I have tried changing the button by adding a class:
and trying to catch the event with $('.editRow').on("click", function() {} event with the same results.
You have a typo onlick instead of onclick.
Also, you could consider to use passive event listener as:
$(document).on("click", <target>,<your function>});
where <target> is the jquery selector for you button
and <your function> your callback.
This would increase readability and as well helps to keep the separation between HTML and JS. And also work for dynamically inserted targets.
Thanks to kmgt. If it was a snake it would have bit me. Have to use 'onclick' instead of 'onlick'.
First of all I agree with #dmitrii-g that you should use event-delegation to be able to handle any events on elements, that were added after DOM was rendered. (added dynamically). After that you should try to debug/print to console any information needed to ensure that you are passing correct values into your function. I've prepared sample example which will demonstrate this approach:
const result = [{
weigh_date: '01/01/2019',
weight: '200lbs',
id: 1,
waist: 'waist',
upperBp: 'upperBp',
lowerBp: 'lowerBp',
comment: 'comment'
},
{
weigh_date: '01/01/2015',
weight: '100lbs',
id: 2,
waist: 'waist',
upperBp: 'upperBp',
lowerBp: 'lowerBp',
comment: 'comment'
}
];
function buildTable() {
if (result != null) {
$('#measurements tbody tr').remove();
result.forEach(function(measurement) {
var message = "<tr><td>" + measurement.weigh_date + "</td>";
message += "<td>" + measurement.weight + "</td>";
message += "<td><input type='hidden' value='" + measurement.id + "'>" + measurement.waist + "</td>";
message += "<td>" + measurement.upperBp + "</td>";
message += "<td>" + measurement.lowerBp + "</td>";
message += "<td>" + measurement.comment + "</td>";
message += "<td><button type='button' class='btn btn-edit btn-outline-warning' id='" + measurement.id + "'>Edit</button> ";
message += "<button type='button' class='btn btn-delete btn-outline-danger' id='" + measurement.id + "'>Remove</button></td></tr>";
$('#measurements').append(message);
});
}
}
$('#measurements').on('click', '.btn-edit', function() {
const id = $(this).attr('id');
console.log('ID to be edited: ' + id);
// your stuff here
});
$('#measurements').on('click', '.btn-delete', function() {
const id = $(this).attr('id');
console.log('ID to be deleted: ' + id);
// your stuff here
});
buildTable();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="panel panel-info">
<div class="panel-heading text-center">Past measurements</div>
<div class="panel-body">
<table class="table table-striped" id="measurements">
<thead class="thead-dark">
<th scope="col">Date</th>
<th scope="col">Weight</th>
<th scope="col">Waist</th>
<th scope="col">Systolic (Upper)</th>
<th scope="col">Diastolic (Lower)</th>
<th scope="col">Comment</th>
<th scope="col">Action</th>
</thead>
<tbody>
</tbody>
</table>
<div class="row"> </div>
</div>
</div>
try this
$(document).on("click","tr",function() {
console.log(this,"click");
});
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)