I want to add the radio button to the dynamically created table.
This is the HTML code where I am adding the dynamically created object.
<div class="row container">
<div class=" col m12 l6 s12" style="height:200px; overflow:scroll;">
<table id="staff">
</table>
</div>
<div class=" col m12 l6 s12" style="height:200px; overflow:scroll;">
<table id="patient">
</table>
</div>
</div>
Here is the Jquery Code for the website
$.ajax({
type: "POST",
url: "/public/src/management/serverfile/selectstaffandpat.php",
dataType: "text",
error: function (request, error) {
console.log(arguments);
alert(" Can't do because: " + error);
},
success: function (JSONObject) {
var peopleHTML = "";
var tempjsonval = JSON.parse(JSONObject);
var str1 = "<tr><th colspan=\"4\">Staff</th></tr><tr><th>Select</th><th>ID</th><th>FirstName</th><th>LastName</th></tr>";
var count_staff = tempjsonval.staff.length;
var count_patient = tempjsonval.patient.length;
for (i = 0; i < count_staff; i++) {
str1 += "<tr><td><input type=\"radio\" name=\"staff\" value=\"" +
tempjsonval.staff[i].s_id +
"staff\" ></input></td><td>" +
tempjsonval.staff[i].s_id +
"</td><td>" +
tempjsonval.staff[i].firstname +
"</td><td>" +
tempjsonval.staff[i].lastname +
"</td></tr>"
}
document.getElementById("staff").innerHTML = str1;
str1 = "";
str1 = " <tr><th colspan=\"3\">Patient</th></tr><tr><th>ID</th><th>FirstName</th><th>LastName</th></tr>";
for (i = 0; i < count_patient; i++) {
str1 += "<tr><td>" +
tempjsonval.patient[i].p_id +
"</td><td>" +
tempjsonval.patient[i].firstname +
"</td><td>" +
tempjsonval.patient[i].lastname +
"</td></tr>"
}
document.getElementById("patient").innerHTML = str1;
}
});
});
There is input created but the radio button is not shown. Can anyone please provide a way to add a radio button with dynamic value.
this is the image where I am getting this output
Please check this one needs to changes some JSON data to ajax response data.
For testing check working demo Click here
HTML content
<div class="row container">
<div class=" col m12 l6 s12" style="height:200px; overflow:scroll;">
<table id="staff">
</table>
</div>
<div class=" col m12 l6 s12" style="height:200px; overflow:scroll;">
<table id="patient">
</table>
</div>
</div>
Javascript Code
var JSONObject = '{"staff":[{"s_id":1,"firstname":"A","lastname":"B"},{"s_id":1,"firstname":"A","lastname":"B"}],"patient":[{"p_id":1,"firstname":"A","lastname":"B"},{"p_id":1,"firstname":"A","lastname":"B"}]}';
var peopleHTML = "";
var tempjsonval = JSON.parse(JSONObject);
console.log(tempjsonval);
var str1 = "<tr><th colspan=\"4\">Staff</th></tr><tr><th>Select</th><th>ID</th><th>FirstName</th><th>LastName</th></tr>";
var count_staff = tempjsonval.staff.length;
var count_patient = tempjsonval.patient.length;
for (i = 0; i < count_staff; i++) {
str1 += "<tr><td><input type=\"radio\" name=\"staff["+i+"]\" value=\"" +
tempjsonval.staff[i].s_id +
"staff\" ></input></td><td>" +
tempjsonval.staff[i].s_id +
"</td><td>" +
tempjsonval.staff[i].firstname +
"</td><td>" +
tempjsonval.staff[i].lastname +
"</td></tr>"
}
document.getElementById("staff").innerHTML = str1;
str1 = "";
str1 = " <tr><th colspan=\"3\">Patient</th></tr><tr><th>ID</th><th>FirstName</th><th>LastName</th></tr>";
for (i = 0; i < count_patient; i++) {
str1 += "<tr><td><input type=\"radio\" name=\"patient["+i+"]\" value=\"" + tempjsonval.patient[i].p_id + "patient\" ></input></td><td>" +
tempjsonval.patient[i].firstname +
"</td><td>" +
tempjsonval.patient[i].lastname +
"</td></tr>"
}
document.getElementById("patient").innerHTML = str1;
OutPut
Note: you need to prepared radio button unique or dynamic either prepared array variable.
$.ajax({
type: "POST",
url: "/public/src/management/serverfile/selectstaffandpat.php",
dataType: "text",
error: function (request, error) {
console.log(arguments);
alert(" Can't do because: " + error);
},
success: function (JSONObject) {
var peopleHTML = "";
var tempjsonval = JSON.parse(JSONObject);
var str1 = `<tr><th colspan="4">Staff</th></tr>
<tr>
<th>Select</th>
<th>ID</th>
<th>FirstName</th>
<th>LastName</th>
</tr>`;
var count_staff = tempjsonval.staff.length;
var count_patient = tempjsonval.patient.length;
for (i = 0; i < count_staff; i++) {
str1 +=`<tr>
<td><input type="radio" name="staff" value="${tempjsonval.staff[i].s_id} staff /></td>
<td>${tempjsonval.staff[i].s_id}</td><td>
${tempjsonval.staff[i].firstname}</td>
<td>${tempjsonval.staff[i].lastname}</td></tr>`}
document.getElementById("staff").innerHTML = str1;
str1 = "";
str1 = `<tr>
<th colspan="3">Patient</th>
</tr>
<tr>
<th>ID</th>
<th>FirstName</th>
<th>LastName</th>
</tr>`;
for (i = 0; i < count_patient; i++) {
str1 +=`<tr>
<td>${tempjsonval.patient[i].p_id}</td>
<td>${tempjsonval.patient[i].firstname}</td>
<td>${tempjsonval.patient[i].lastname}</td>
</tr>`
}
document.getElementById("patient").innerHTML = str1;
}
});
try to use template literal it's a nice feature
Related
I have a function which loads a html table with sql data query and a html page to display the table when i click the button but it is not showing the table, it just shows the url changing to match my search but does not display the table
Function code:
function Search()
{
var search = new Object;
search.restaurantName = document.getElementById("searchinput").value; //get input
var searchrestaurant = new XMLHttpRequest();
searchrestaurant.open("POST", Search_url, true);
searchrestaurant.setRequestHeader("Content-Type", "application/json");
searchrestaurant.onload = function()
{
search_array = JSON.parse(request.responseText);
result();
}
searchrestaurant.send(JSON.stringify(search));
}
function result()
{
var table = document.getElementById("result");
table.innerHTML = "";
result = search_array.length
for (var count = 0; count < result; count++)
{
// data from sql
var restaurant_name = search_array[count].restaurant_name;
var Description = search_array[count].Description;
var location = search_array[count].location;
var thumbnail = search_array[count].thumbnail;
var price = search_array[count].price;
var rating = search_array[count].avg_rating;
//table to show all sql data
var AllrestaurantTable = "<table class = fixed style=width:100% border=1px>" +
"<tr>"+
"<td>" +"<a href = 'detailed_restaurant.html' target ='_blank'>"+"<img src ='" + thumbnail + "'style=width:100px;height:100px;></img>"+"</td>" +
"<td>"+"<a href = 'detailed_restaurant.html' target ='_blank'>"+ restaurant_name + "</td>" +
"<td>"+ location + "</td>" +
"<td>"+ Description + "</td>" +
"<td>"+ price + "</td>" +
"<td>"+ rating + "</td>"
"</tr>" +
"</table>";
table.insertAdjacentHTML('beforeend', AllrestaurantTable);
}
}
Html:
<body>
<form id = "SearchForm">
<label>Search </label>
<input type="text" id="searchinput" name="restaurantName">
<input type="button" onclick="Search()" value="Submit">
</form>
<div class="container"></div>
<div id="result" class="row"></div>
</div>
I have already loaded the script into the html site but it is just take my input and does not display the table i created
Concatenation operator is missing after "<td>" + rating + "</td>".
Add the + operator. like "<td>" + rating + "</td>" +.
function result() {
var table = document.getElementById("result");
table.innerHTML = "";
result = 5
for (var count = 0; count < result; count++) {
// data from sql
var restaurant_name = 1;
var Description = 'ddf';
var location = 'location';
var thumbnail = 1;
var price = 'Price';
var rating = 'rating';
//table to show all sql data
var AllrestaurantTable = "<table class = fixed style=width:100% border=1px>" +
"<tr>" +
"<td>" + "<a href = 'detailed_restaurant.html' target ='_blank'>" + "<img src ='" + thumbnail + "'style=width:100px;height:100px;></img>" + "</td>" +
"<td>" + "<a href = 'detailed_restaurant.html' target ='_blank'>" + restaurant_name + "</td>" +
"<td>" + location + "</td>" +
"<td>" + Description + "</td>" +
"<td>" + price + "</td>" +
"<td>" + rating + "</td>" +
"</tr>" +
"</table>";
table.insertAdjacentHTML('beforeend', AllrestaurantTable);
}
}
result();
<div id="result" class="row"></div>
</div>
You have to pass the search array in your result function.
function Search() {
var search = new Object;
search.restaurantName = document.getElementById("searchinput").value; //get input
var searchrestaurant = new XMLHttpRequest();
searchrestaurant.open("POST", Search_url, true);
searchrestaurant.setRequestHeader("Content-Type", "application/json");
searchrestaurant.onload = function () {
search_array = JSON.parse(request.responseText);
result(search_array);
}
searchrestaurant.send(JSON.stringify(search));
}
Hope this will work.
I have a small project working on. When I add items to my array they will display in a table below my fields.
My problem is that when I try to append a checkbox it returns [object, Object].
My HTML:
<div class="container">
<input id="list-input" />
<select id="select-status">
<option value="on-going">on-going</option>
<option value="completed">completed</option>
</select>
<button id="add">Add To List</button>
<button id="delete">Remove From List</button>
</div>
<div class="container">
<h1>Your List</h1>
<div id="mylist">
<table id="mylist">
<thead>
<th>ID Number</th>
<th>Description</th>
<th>Status</th>
</thead>
<tbody>
</tbody>
</table>
</div>
<button id="clear">clear</button>
</div>
My JavaScript:
var tasks = [];
var count = 0;
$('document').ready(function(){
$('#add').click(function() {
var desc = $.trim($('#list-input').val());
var status = $('#select-status option:selected').val();
var id = Date.now();
item = {};
if (!desc) {
item.id = "";
alert("Input a description");
return;
}
item.id = id;
item.description = desc;
item.status = status;
tasks.push(item);
var tr = "<tr>";
var td1 = "<td id="+ item.id +">" + item.id + "</td>";
var td2 = "<td>" + item.description + "</td>";
var td3 = "<td>" + item.status + "</td>";
var td4 = "<td>" + $('<input/>',{'type':'checkbox'}) + "</td>" ;
$("#mylist tbody").append(tr + td1 + td2 + td3 + td4);
//clear input field
$('#list-input').val('');
});
//clear list function
$('#clear').click(function(){
tasks = [];
$('#mylist tbody').empty();
setTimeout(function(){
alert("List is now empty!");
}, 500);
});
//remove list function
$('#delete').on('click', function() {
$('#mylist input:checked').closest('#item').remove();
});
});
This line:
var td4 = "<td>" + $('<input/>',{'type':'checkbox'}) + "</td>" ;
creates a jQuery object and then concatenates it with a string. Most objects don't implement toString (and jQuery objects don't), so you get the default "[object Object]" string.
You're already working in markup, keep doing that:
var td4 = "<td><input type='checkbox'></td>" ;
...or switch over the code to working with objects instead.
I am trying to populate a table using jquery on my website. When I write the HTML manually on the HTML page it works, but when I replace it with a div and use jquery to append html to it, it inserts the HTML just above the table headers.
It is pulling information that the user created on a table on a different tab to ask the user to confirm the input before submitting.
The row I manually enter (Adult, 4.99, 0,) all appear as they should, but the rows appended to div ticketconfirmation appear above the table. The Jquery is called once the user presses continue on the page where they originally entered the data.
Can anyone explain why this is happening?
Thanks
HTML
<table class="table table-hover">
<thead>
<tr>
<th>Ticket Name</th>
<th>Ticket Price</th>
<th>Max Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>Adult/td>
<td>4.99</td>
<td>0</td>
</tr>
<div id="ticketconfirmation"></div>
</tbody>
JQuery
function getNodes() {
console.log("Getting node info");
$("#ticketconfirmation").text('');
var table = $('#sample_editable_1').DataTable();
var data = table.rows().data();
for (var i = 0; i < data.length; i++) {
$("#ticketconfirmation").append('<tr>');
var row = table.row(i).data();
$("#ticketconfirmation").append(
"<td>" + row[0] + " </td><td> " + row[1] + " </td><td> "
+ row[2] + "</td></tr>");
}
};
remove your <div id="ticketconfirmation"></div>
and try this one:
var newRow;
for (var i = 0; i < data.length; i++) {
var row = table.row(i).data();
newRow = "<tr><td>" + row[0] + " </td><td> " + row[1] + " </td><td> "
+ row[2] + "</td></tr>";
$('table.table tbody').append(newRow);
}
for (var i = 0; i < data.length; i++) {
var tableRow = $('<tr></tr>');
var row = table.row(i).data();
tableRow.append("<td>" + row[0] + " </td><td> " + row[1] + " </td><td> " + row[2] + "</td>");
$("#ticketconfirmation").append(tableRow);
}
You can give the id ticketconfirmation on tbody and remove that div.
I am trying to prevent the player from getting added again with the new value, rather I would like to just update the quantity..
HTML
<div class="playerTypeBlock" data-player-type-id="1" data-player-value="10.00">
<div class="heading">Ninja</div>
<div class="price">$10</div> <a class="addToTeam" href="#">Add player</a>
</div>
<hr>
<div class="playerTypeBlock" data-player-type-id="2" data-player-value="20.25">
<div class="heading">Samurai</div>
<div class="price">$20.25</div> <a class="addToTeam" href="#">Add player</a>
</div>
<hr>
<table class="teams" border="1">
<thead>
<tr>
<th>Players</th>
<th>Quantity</th>
</tr>
</thead>
<tbody class="totalPlayers"></tbody>
</table>
<div class="total">
<span>Total: $</span>
<span class="amount" id="totalvalue">0.00</span>
</div>
I tried using this when appending the table row, but not getting the desired result
JavaScript
var addToTeam = document.getElementsByClassName('addToTeam'),
parentElement = document.getElementsByClassName('playerTypeBlock'),
playerName = document.getElementsByClassName('heading'),
totalVal = document.getElementById('totalvalue'),
tableBody = document.querySelector('.totalPlayers');
var updatePlayers = function (evt) {
evt.preventDefault();
var amount = totalVal.innerHTML,
productId = this.parentElement.getAttribute('data-player-type-id'),
productPrice = this.parentElement.getAttribute('data-player-value'),
playerName = this.parentNode.querySelector('.heading').innerHTML,
updateTotal = parseFloat(amount) + parseFloat(productPrice);
var quantity = parseInt($(this).data('click'), 10) || 0;
quantity++;
$(this).data('click', quantity);
totalVal.innerHTML = Math.round(updateTotal * 100) / 100;
//adding the the table row here...
$('table .totalPlayers').append('<tr><td>' + playerName + '</td><td>' + quantity + ' </td></tr>');
};
for (var i = 0; i < addToTeam.length; i++) {
addToTeam[i].addEventListener('click', updatePlayers);
}
See Demo
Check quantity and append new row if it's 1 otherwise modify quantity cell:
if (quantity > 1) {
$('table .totalPlayers').find('#player-' + playerId + ' .quantity').text(quantity);
}
else {
$('table .totalPlayers').append('<tr id="player-' + playerId + '"><td>' + playerName + '</td><td class="quantity">' + quantity + ' </td></tr>');
}
Demo: http://jsfiddle.net/zx65uv8a/12/
This line the problem?
$('table .totalPlayers').append(
'<tr><td>' + playerName + '</td>' +
'<td>' + quantity + ' </td></tr>');
You are using append() so you'll always be adding and not replacing.
If you can add something unique to a class or id then you can replace it that way. i.e.
$('table .totalPlayers').append(
'<tr id="' + playerId + '">' +
'<td>' + playerName + '</td>' +
'<td class="quantity">' + quantity + ' </td></tr>');
Then to update
$('#' + playerId + ' .quantity').html(New value here);
this is my view
im trying to access row index using this method
$("input.deliverQty").focusout(function (e) {
var table = document.getElementById('invoiceDetailTbl');
var DeliverQty = $(this).val();
var rowId = $(this).closest('tr').attr('rowIndex');
//var OrderQty = $(this).closest('tr').find('input.payingAmt').val();
var OrderQty = table.rows[parseInt(rowId) + 1].cells[2].childNodes[0].data;
but result was undefined
i'm append my table like this
for (var i = 0; i < data[0].itemDetails.length; i++) {
itmCode = data[0].itemDetails[i].item_Code;
itmName = data[0].itemDetails[i].item_Name;
OQty = parseInt(data[0].itemDetails[i].item_Qty);
//netAmt = parseFloat(data[i].Net_Amt).toFixed(2);
//paidAmt = parseFloat(data[i].Paid_Amt).toFixed(2);
//balance = (parseFloat(netAmt) - parseFloat(paidAmt)).toFixed(2); //id = "damt['+i+']"
$("#invoiceDetailTbl tbody").append("<tr id=" + i + ">" + "<td>" + itmCode + "</td>" + "<td>" + itmName + "</td>" + "<td>" + OQty + "</td>" + "<td>" + '<input type="text" class="deliverQty form-control input-sm" style="width: 100px;" placeholder="Deliver Qty" id="dqty">' + "</td>" + "<td>" + '<span class="glyphicon glyphicon-trash"></span>' + "</td>" + "</tr>");
//noOfItems = parseInt(noOfItems) + parseInt(OQty);
//noOfProducts = parseInt(noOfProducts) + 1;
}
rowIndex is not an attribute, so try .prop()
var log = (function() {
var $log = $('#log');
return function(msg) {
$('<p/>', {
text: msg
}).appendTo($log)
}
})();
jQuery(function() {
$('tr input').each(function() {
var rowId = $(this).closest('tr').attr('rowIndex');
log('attr: ' + rowId);
rowId = $(this).closest('tr').prop('rowIndex');
log('prop: ' + rowId);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input />
</td>
</tr>
<tr>
<td>
<input />
</td>
</tr>
</table>
<div id="log"></div>