var students = [
["test", "test", "test"],
["test", "test", "test"]
];
students.sort();
function display() {
for (i = 1; i < students.length + 1; i++) {
document.write("<tr>");
document.write("<td>" + (i) + "</td>");
document.write("<td>" + students[i - 1][0] + "</td>");
document.write("<td>" + students[i - 1][1] + "</td>");
document.write("<td>" + students[i - 1][2] + "</td>");
document.write("<td><input type='number' class='form-control' id='quiz" + i + "' ></td>");
document.write("<td><input type='number' class='form-control' id='reqt" + i + "'></td>");
document.write("<td><input type='number' class='form-control' id='exam" + i + "'></td>");
document.write("<td><input type='number' class='form-control' id='pg" + i + "' readonly></td>");
document.write("</tr>");
}
}
function AddData() {
var AddName;
var AddCourse;
var AddBDay;
var Data;
AddName = document.getElementById('Addname').value;
AddCourse = document.getElementById('AddCourse').value;
AddBDay = document.getElementById('AddBDay').value;
if (AddName != "" && AddCourse != "" && AddBDay != "") {
Data = [AddName, AddCourse, AddBDay];
students.push(Data);
console.log(students);
display();
} else {
alert("Invalid Input");
}
}
document.write is very very old-school and it's very rarely used any more for many reasons.
You can either create a string variable that you can then add (concatenate) new strings to, or you can use more modern methods like in the example below which uses map to iterate over the array to create a new array of strings, and then join that array up into one HTML string.
const students = [
["test", "test", "test"],
["test", "test", "test"]
];
function getHtml(students) {
return students.map(arr => {
return `
<tr>
<td>${arr[0]}</td>
<td>${arr[1]}</td>
<td>${arr[2]}</td>
</tr>
`
}).join('');
}
const table = document.querySelector('table');
table.innerHTML = getHtml(students);
<table></table>
You haven't posted any HTML, but assuming you have a <table id="x"> or <tbody id="x">, modify the display function as below:
function display() {
let html = '';
students.map((item, i) => {
html += "<tr>";
html += "<td>" + (i+1) + "</td>";
html += "<td>" + item[0] + "</td>";
html += "<td>" + item[1] + "</td>";
html += "<td>" + item[2] + "</td>";
html += "<td><input type='number' class='form-control' id='quiz" + i + "' ></td>";
html += "<td><input type='number' class='form-control' id='reqt" + i + "'></td>";
html += "<td><input type='number' class='form-control' id='exam" + i + "'></td>";
html += "<td><input type='number' class='form-control' id='pg" + i + "' readonly></td>";
html += "</tr>";
});
document.getElementById("x").innerHTML = html;
}
Also, document.write is rarely to never used. More here.
element.innerHTML is generally used when you want to perform some DOM manipulation as a result of an API call or any other event, as in your case.
Related
I have got the below JSON as result from database through calll of json_encode
[
{
"id":1,"FullName":"Duce",
"subjects": [
{
"id":1,
"SubjectName":"Phy",
"pivot":{
"student_id":1,
"subject_id":1
}
}
],
"topics": [
{
"id":1,
"TopicName":"Meas",
"Subject_id":"1",
"pivot":{
"student_id":1,
"topic_id":1,
"Price":15000,
}
}
]
}
]
I need to achive something like this
------------------------------------------------------------------------------------------------------------------
ID Subject Name Topics Name Price Action
--------------------------------------------------------------------------------------------------------------------
1 Phy Meas 15000 X
2 ----- ---- -----
-------------------------------------------------------------------------------------------------------------------
i tried on using Jquery Ajax each methods to pass through every object within a data responses as below but got an intended results
let rows = '';
$.get(URL_GET_STUDENT,
function (data ,status) {
console.log(data);
$.each(data ,function (key ,value) {
$("#FullName").val(value.FullName);
$.each(value.subjects ,function (key1 ,value1 ) {
rows += "<tr>" +
"<td>" +
"<select class='form-control subject_selected' name='subject[]' id='subject' data-id='0' required>" +
"<option>"+ value1.SubjectName +"</option>" +
"</select>" +
"</td>" +
"<td>";
});
$.each(value.topics ,function (key2 ,value2 ) {
rows += "<select class='form-control topic_selected' name='topic[]' id='topic' data-id='0' required>" +
"<option>" + value2.TopicName + "</option>" +
"</select>" +
"</td>" +
"td>" +
"<input type='text' class='form-control Amount' name='Amount[]' id='Amount' value='"+ value2.TopicName +"'/>" +
"</td>" +
"<td>" +
"<a href='javascript:void(0)' class='btn btn-danger remove'>X</a>" +
"</td>"+
"</tr>";
});
});
$("#table_tuition_fee").append(rows);
});
Which is like below
Anyone who can help me to achieve the above result? I real appreaciate your help?
I have created one form and form after submitting the value I want to show them in a table. In table I have one section where I want to delete or edit a particular user on a button. But when I am passing the id to that function I am getting error saying that refernece error occurred!
function getEmployeeDetails() {
for (var i = 0; i < userArray.length; i++) {
var tr = "<tr>";
tr +=
"<td class='table-data'/td>" +
userArray[i].id +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].name +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].email +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].gender +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].role +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].english +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].hindi +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].othersLang +
"</td>" +
"<td class='table-data'/td>" +
userArray[i].description +
"</td>" +
"<td class='table-data'/td>" +
"<button onclick='deleteUser( userArray[i].id )'>Delete</button> || <button onclick='editUser( userArray[i].id )'>Edit</button>" +
"</td>" +
"</tr>";
tbody.innerHTML += tr;
}
}
function deleteUser(id) {
console.log("delteuser", typeof id, id);
}
function editUser(id) {
console.log("edit", id);
}
Where I have made the mistakes?
The problem is in the string concatenation you are using in the onClick event.
You can use a backtick character instead.
Copy-paste and check the below code.
<html>
<body>
<table id="table"></table>
<script>
getEmployeeDetails();
function getEmployeeDetails() {
let userArray = [{ id: 1 }, { id: 2 }];
var tr = "";
for (var i = 0; i < userArray.length; i++) {
tr +=
`<td class="table-data">
<button onclick="deleteUser(` +
userArray[i].id +
`)">Delete</button> || <button onclick="editUser( ` +
userArray[i].id +
`)">Edit</button>
</td>`;
}
document.getElementById("table").innerHTML = tr;
}
function deleteUser(id) {
console.log("delteuser", typeof id, id);
}
function editUser(id) {
console.log("edit", id);
}
</script>
</body>
</html>
Change
<button onclick='deleteUser( userArray[i].id )'>
To something like
<button onclick='deleteUser('+userArray[i].id+')'>
In your current attempt you are not inserting the value of userArray[i].id but the variable userArray[i].id which is kind of nonsense.
Same story with the editUser function
I want to get the value of the input fill from a function to another function but I am not sure how.
From this funtion input fill:
$("#buttonDone4").click(function () {
function productAddToTable() {
$("#table").fadeIn();
// First check if a <tbody> tag exists, add one if not
if ($("#table tbody").length == 0) {
$("#table").after("<tbody></tbody>");
}
// Append product to the table
$("#table").append(
"<tr>" +
"<td>" + document.getElementById("perimeter2").innerHTML + "</td>" +
"<td>" + "4" + "</td>" +
"<td>" + "<input type='text' name='periAns' size='10'/>" + "</td>" +
"</tr>"
);
}
productAddToTable();
$("#buttonDone4").fadeOut();
$(".p1").fadeIn();
$("#buttonCheck").fadeIn();
});
To this function:
$("#buttonCheck").click(function () {
var pa = document.getElementByName["periAns"].value;
var peri = (document.getElementById("perimeter2").innerHTML / 4);
if(peri == pa ){
console.log("yes");
}else{
console.log("no");
}
});
Put ID to the inputs and use jquery.
$("#table").append(
"<tr>" +
"<td>" + document.getElementById("perimeter2").innerHTML + "</td>" +
"<td>" + "4" + "</td>" +
"<td>" + "<input type='text' id ='periAns' size='10'/>" + "</td>" +
"</tr>"
);
}
$("#buttonCheck").click(function () {
var pa = Number($("#periAns").val()) //assuming this is an input
var peri = Number(document.getElementById("perimeter2").innerHTML)
var finPeri = peri / 4
if(finPeri == pa ){
console.log("yes");
}else{
console.log("no");
}
});
I'm getting the following error in my javascript. As the title states, this code is working on my localhost, but not when I put it onto my server
Uncaught TypeError: Cannot read property 'push' of null
at addItemToCart (shoppingCart.js:36)
at HTMLButtonElement.<anonymous> (shoppingCart.js:193)
at HTMLDocument.dispatch (jquery-1.11.1.min.js:3)
at HTMLDocument.r.handle (jquery-1.11.1.min.js:3)
I have identified that just before this push function is called that the cart variable is indeed null, but I declare it globally as an empty array, so I'm not sure why that would be.
Code for the function its failing on
var cart = [];
function addItemToCart(name, price, count, id, shortName) {
for (var i in cart) {
if (cart[i].id === id) {
cart[i].count += count;
saveCart();
for (var i in cart) {
if (cart[i].id == 500 && id != 500) {
removeItemFromCart(500);
alert('because you changed your cart, you will have to reapply your coupon');
}
}
return;
}
}
for (var i in cart) {
if (cart[i].id == 500 && id != 500) {
removeItemFromCart(500);
alert('because you changed your cart, you will have to reapply your coupon');
}
}
var item = new Item(name, price, count, id, shortName);
console.log(cart);
cart.push(item);
saveCart();
}
The error happens at teh cart.push(item); line because cart is null and can not be pushed to. Anymore information someone may need to help feel free and I will shoot it your way.
Thanks in advance!!!
edit:
function displayCart() {
console.log("*** display Cart ***");
var cartArray = listCart();
var output = "<tr><th>Items</th><th>Quantity</th><th>Price</th></tr>";
var output2 = "<tr><th> </th><th>Product name</th><th>Product price</th><th>Quantity</th><th>Total</th></tr>";
var output3 = " <tr><th>Product(s)</th></tr>";
var output4 = "";
console.log(listCart());
for (var i in cartArray) {
output += "<tr class='item'><td><div class='delete' id='removeItem' data-id='" + cartArray[i].id + "'></div>" + cartArray[i].name + "</td><td><input type='text' value='" + cartArray[i].count + "' readonly></td> <td class='price'>" + cartArray[i].price + "</td></tr>"
output2 += "<tr class='item'>"
+ "<td class='thumb'><a href='" + cartArray[i].id + "-item.php'><img src='img/catalog/product-gallery/" + cartArray[i].id + ".png' alt='Product Image'/></a></td>"
+ "<td class='name'><a href='" + cartArray[i].id + "'-item.php'>" + cartArray[i].name + "</a></td>"
+ "<td class='price'>$" + cartArray[i].price + "</td>"
+ "<td class='qnt-count'>"
+ "<a class='incr-btn' href='#' id='oneless' data-id='" + cartArray[i].id + "'>-</a>"
+ "<input class='quantity form-control' type='text' value=' " + cartArray[i].count + " '>"
+ "<a class='incr-btn' id='onemore' data-productid='" + cartArray[i].id + "' data-name='" + cartArray[i].name + "' data-quantity='" + cartArray[i].count + "' href='#'>+</a>"
+ "</td>"
+ "<td class='total'>$<em id='test'>" + cartArray[i].total + "</em></td>"
+ "<td class='delete' id='removeAllFromCart' data-id='" + cartArray[i].id + "'><i class='icon-delete'></i></td>"
+ "</tr>";
output3 += " <tr><td class='name border'>" + cartArray[i].shortName + "<span>x" + cartArray[i].count + "</span></td>"
+ "<td class='price border'>$" + cartArray[i].total + "</td></tr>";
if ($("#offerCount").attr("data-id") == cartArray[i].id) {
output4 += +"<a class='incr-btn' href='#' id='oneless' data-id='" + cartArray[i].id + "'>-</a>"
+ "<input class='quantity form-control' type='text' value=' " + cartArray[i].count + " '>"
+ "<a class='incr-btn' id='onemore' data-productid='" + cartArray[i].id + "' data-name='" + cartArray[i].name + "' data-quantity='" + cartArray[i].count + "' href='#'>+</a>";
}
}
output3 += " <tr><td class='th border'>Shipping</td><td class='align-r border'>Free shipping</td></tr>"
+ "<tr><td class='th'>Order total</td><td class='price'>$" + totalCart() + "</td></tr>"
$("#offerCount").html(output4);
$("#productDisplay").html(output3);
$("#showFullCart").html(output2);
$("#showCart").html(output);
$("#cartTotal").html(totalCart());
$("#totalCart").html(totalCart());
$("#myCartTotal").html(totalCart());
$("#showmyTotal").html(totalCart());
$("#cartCount").html(countCart());
}
function addCouponToCart(coupon) {
if (coupon == 'coupon10' && couponsAdded == 0) {
var couponReduce = -(totalCart() * .1).toFixed(2);
addItemToCart('10% off Coupon', couponReduce, 1, 500, '10% off');
couponsAdded += 1;
saveCoupon();
}
displayCart();
}
function countCart() {
var totalCount = 0;
for (var i in cart) {
totalCount += cart[i].count;
}
return totalCount;
}
function removeItemFromCartAll(id) {
for (var i in cart) {
if (cart[i].id === id) {
cart.splice(i, 1);
break;
}
}
for (var i in cart) {
if (cart[i].id == 500 && id != 500) {
removeItemFromCart(500);
alert('because you changed your cart, you will have to reapply your coupon');
}
}
saveCart();
}
Code that calls the addCouponToCart Function whenever a post gets set.
<?php if (isset($_POST['coupon_code'])) { ?>
<script>
addCouponToCart(coupon);
</script>
<?php } ?>
#codenoname Provided the correct answer of checking for the null cart. That solved the issue, ultimately a lot of functions were not being defined properly. I had wrapped the entire code in a document ready function which seemed to be the issue. Whenever I removed that it worked. Thank you all for your input.
if (!cart) {
cart = [];
}
I am creating a dynamic tr/td based on json data using below code.
for (i = 0; i < dataPoolJSON.length; i++) {
html += "<tr id ='row" + i + "' value ='" + dataPoolJSON[i].msisdn + "'><td><div class='group'><label id='label" + i + "' for='numView" + dataPoolJSON[i].msisdn + "' class='ch-control'>";
html += "<input id='numView" + dataPoolJSON[i].msisdn + "' type='radio' class='iradio_minimal' value='" + i + "' name='msisdnSelected'/>" + dataPoolJSON[i].msisdn;
html += "</label></div></td><td class='hidden-xs'><a id='viewUsage" + i + "' class='viewUsage' onclick='viewDataPoolUsage(this," + dataPoolJSON[i].msisdn + ");return false;' href=''>View Usage</a>";
html += "<div class='pool-usage hidden'></div></td>";
html += "<td><span id='dataAllowed" + i + "'><select>";
if (dataPoolJSON[i].userSetting != null) {
html += "<option selected='selected' value='" + dataPoolJSON[i].userSetting.alertPercentageData1 + "'>" + dataPoolJSON[i].userSetting.alertPercentageData1 + "</option>";
}
html += "</select></span></td></tr>";
}
$('#data-pool tbody').html(html);
Now on click on radio button i need to fetch the msisdn value and current option selected value as but it is not giving me required answer. I am getting the current option selected value but not the msisdn.
function submitNewDataUsagealerts() {
var jsonSubmitData = [];
var selectedData = document.getElementsByName("msisdnSelected");
var i = selectedData.length-1;
for ( j=0; j <= i; j++ ) {
if(selectedData[j].checked) {
var valueCurrent = $('#dataAllowed'+selectedData[j].value).find('option:selected').val();
var row = $('#label'+selectedData[j].value).val();
item = {}
item [0] = valueCurrent;
item [1] = selectedData[j].value;
}
}
}
To get the "value" from a label, use .text() rather than .val().
var row = $('#label'+selectedData[j].value).text();
As your label includes an input and the required text, you can put the text inside a container so that it can be referenced without including the input:
The label code is currently (irrelevant code removed) :
html += "<label id='label" + i + "' for='numView" + dataPoolJSON[i].msisdn + "' class='ch-control'>";
html += "<input id='numView" + dataPoolJSON[i].msisdn + "' type='radio' class='iradio_minimal' value='" + i + "' name='msisdnSelected'/>";
html += dataPoolJSON[i].msisdn;
html += "</label>";
change this to:
html += "<label id='label" + i + "' for='numView" + dataPoolJSON[i].msisdn + "' class='ch-control'>";
html += "<input id='numView" + dataPoolJSON[i].msisdn + "' type='radio' class='iradio_minimal' value='" + i + "' name='msisdnSelected'/>" ;
html += "<span>" + dataPoolJSON[i].msisdn + "</span>";
html += "</label>";
Then your selector can be:
var row = $('#label'+selectedData[j].value + ">span").text();
Alternatively, move the input out of the label as you're already using label for=:
html += "<input id='numView" + dataPoolJSON[i].msisdn + "' type='radio' class='iradio_minimal' value='" + i + "' name='msisdnSelected'/>" ;
html += "<label id='label" + i + "' for='numView" + dataPoolJSON[i].msisdn + "' class='ch-control'>";
html += dataPoolJSON[i].msisdn
html += "</label>";
Then your selector can be:
var row = $('#label'+selectedData[j].value).text();
var msg = document.getElementById('lbltxt').innerHTML;
alert(msg);
<label id="lbltxt" style="display:none">Test</label>
HTML Code
<label id="mylabel" />
JS Code
var lavelValue = $("#mylabel").text();