I am making a table in JavaScript using template literals, so I don't have access to each row of my table. I have a form in which my table is set and I have a number input at the end of each row. Right now, my program is only sending the quantity of the fist object to the console, but I need all of the quantities according to the id so that i can make a total at the end of my shopping cart.
I don't know if I could make a loop that goes through each row and tell me the id, price and quantity but that would be my first instinct. I am still new to JavaScript so I don't really know where to go from here.
Here is my JavaScript code:
//load JSON file
var articles = ""
var txt = ""
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
articles = xmlhttp.responseText;
processArticles(articles);
var form = document.getElementById('formtable');
var quantity = document.getElementById('quantity');
form.onsubmit = function(e) {
e.preventDefault();
console.log("HI");
console.log(quantity.value);
};
}
};
xmlhttp.open("GET","../articles.json",true);
xmlhttp.send();
function processArticles(articles) {
txt = JSON.parse(articles);
var tableStart = `
<h2>Liste des articles</h2>
<form id="formtable">
<table>
<tr>
<th>ID</th>
<th>Article</th>
<th>Prix</th>
<th>Prix-Retour</th>
<th>Quantitée maximale</th>
<th>Projet</th>
<th>Quantitée</th>
</tr>`;
var tableEnd = `
</table>
<input type="submit">
</form>`;
function articlesTemplate(txt) {
return `
<tr>
<td>${txt.ID}</td>
<td>${txt.Article }</td>
<td>${txt.Prix}</td>
<td>${txt.PrixRetour}</td>
<td>${txt.QuantiteeMaximale}</td>
<td>${txt.Projet}</td>
<td><input type="number" id="quantity" min="1" max="5"></td>
</tr>
`;
}
let mctxt=txt.filter(value=>
value.Projet=="mc");
document.getElementById("tablemc").innerHTML = `
${tableStart}
${mctxt.map(articlesTemplate).join("")}
${tableEnd}
`;
;
}
In my HTML, I just have a div with the id of tablemc.
I want to be able to see the quantity of each item with their id, so that I can make a total amount at the end of my table. Right now, it only sends the quantity of the first item and it doesn't tell me which id it is or what the price of the item is.
Related
Hi I have one issue in MVC JQuery. please resolve this issue. I really appreciate your help. Let me explain you my concern.
Actually I have a dropdown in which there is some list of items and i am just adding them in the table but i want when i select any item and added in the table and again i select that item and trying to add that in the table i will get the alert that "Already Exist". But i am unable to do this.
Let me share my code with you.
$("#addToList").click(function (e) {
e.preventDefault();
if ($.trim($("#StockID").val()) == "" || $.trim($("#Quantity").val()) == "" || $.trim($("#Price").val()) == "")
return;
var productName = $("#StockID option:selected").text();
var pid = $("#StockID option:selected").val();
let price = $("#Price").val();
let quantity = $("#Quantity").val();
let detailsTableBody = $("#detailsTable tbody");
var productItem = `<tr>
<td pid=${pid}>
${productName}
</td>
<td><span data-line_qty="${quantity}" data-itemId="0" href="#" class="qtyItem" >${quantity}</span></td>
<td>${price}</td>
<td>${(parseFloat(price) * parseInt(quantity))}</td>
<td><a data-line_total="${(parseFloat(price) * parseInt(quantity, 10))}" data-itemId="0" href="#" class="deleteItem">Remove</a></td>
</tr>`;
detailsTableBody.append(productItem);
calc_total();
clearItem();
});
Let me share my output
You can solve it using HashTable or set. On selecting the item push into hash table as well and check if the item is already in hash table code then show the alert message.
You can implement hashTable like -
var itemsAdded = {};
if(itemsAdded[item]){
alert('Item is already added !');
} else {
itemsAdded[item] = item;
}
Hello all I just want to say thank you in advance. I have a few issues that I would like to address with my shopping cart page. This application is made in flask.
I have a cart that dynamically populates rows in a table with data from a Restful API created with python. At the moment it can also add the prices within the API and display it as the subtotal's html. I can also hit the delete button next to the item and it deletes that particular element out of the API. The issue is I need to be able to update the subtotal html upon deleting the item.
Yes I can hit the delete button and upon refreshing the page it will show the correct subtotal but this is unrealistic.
Upon adding and deleting items in cart I also have a badge on the shopping cart icon in the upper right hand corner that increments according to how many elements are in API. Once I figure out issue with (problem labeled 1) I can figure out how to make the badge decrease upon item deletion. My main issue here is the cart shows no badge upon moving to different tabs of the website. The JS is linked to the base html, but I guess since the java script is not running on those particular pages it's not going to show. Not to sure how to work around this.
If there are no items in cart I would like to hide the subtotal html and order button. But for some reason I can't get it to toggle and don't know where I should put the code to check if there are no items in API.
I'm probably asking too much but if possible please help if you may have any insight. I'll be attaching the code below for javascript, my flask python route, and the html for the cart page.
Pricing pricing.html
p{% extends 'base.html' %}
{% block content %}
<h1>Pricing</h1>
<div class="row">
<div class="container col-sm-6">
<div class="container border">
<table id='table'>
<thead>
<th><h5>Equipment</h5></th>
<th "><h5>Price</h5></th>
</thead>
{% for quip in pricing %}
<tr style="height:25px;" class="border">
<td id='pricewidth'>{{quip}}</td>
<td id='pricewidth' style='text-align:center;'>{{pricing[quip]}}</td>
<td ><button type="button" name="button" class="btn btn-primary">Add</button></td>
</tr>
{% endfor %}
</table>
</div>
</div>
<div class="container col-sm-6">
<table id='cart'>
</table>
<div id='pricefooter'>
<h1 style='margin-top:25px; border-top:.5px black solid;'>Subtotal: $<span id='subtotal'>0</span></h1>
<form action="{{url_for('Order')}}"><button type="submit" name="button" class='btn btn-warning'>Order</button></form>
</div>
</div>
</div>
{% endblock content %}
Cart Javascript pricecart.js
var tablerows = document.getElementById('table').rows.length;
var table = document.getElementById('table');
var cart = document.getElementById('cart');
var subtotal = document.getElementById('subtotal');
var username = document.getElementById('username').innerHTML;
var cartBadge = document.getElementById('cartbadge');
var pricesub = document.getElementById('pricefooter');
// On load cart
window.onload = function wowzers(){
var array = [];
var sum = 0;
// Get Data
var xhr = new XMLHttpRequest();
xhr.open('GET', 'pricing/orders/' + username +'/api', true);
xhr.onload = function(){
var data = JSON.parse(this.response);
cartBadge.innerHTML = data.length
if(xhr.status >= 200 && xhr.status < 400){
for(x in data){
for(key in data[x]){
array.push(Number(data[x][key]));
sum+=Number(data[x][key]);
subtotal.innerHTML = sum;
row = cart.insertRow(-1);
// Delete Data
row.addEventListener('click', function deleterow(){
index = this.rowIndex;
// subtotal.innerHTML = sum-Number(cart.rows[index].cells[1].innerHTML);
$.post('pricing/orders/delete', {
delete_item: index
});
cart.deleteRow(index);
});
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);
cell1.innerHTML = key;
cell2. innerHTML = data[x][key];
cell3. innerHTML = "<button class='btn btn-danger'>Delete</button>"
}
}
console.log(sum);
}else{
console.log(error)
}
}
xhr.send()
}
//Dynamic Cart
for(x = 0; x < tablerows; x++){
table.rows[x].addEventListener('click', addCartItem);
}
function addCartItem(ev){
var array = [];
var sum = 0;
index = this.rowIndex;
equipmentCell = table.rows[index].cells[0];
priceCell = table.rows[index].cells[1];
equipmentName = equipmentCell.innerHTML;
equipmentPrice = priceCell.innerHTML;
// Post Data
$.post('/pricing/orders/' + username + '/api', {
javascript_data: JSON.stringify({[equipmentName]:equipmentPrice})
});
cartrow = cart.insertRow(-1);
// Delete Data
cartrow.addEventListener('click', function deleterow(){
index = this.rowIndex;
// subtotal.innerHTML = sum-Number(cart.rows[index].cells[1].innerHTML);
$.post('pricing/orders/delete', {
delete_item: index
});
cart.deleteRow(index);
});
cell1 = cartrow.insertCell(0);
cell2 = cartrow.insertCell(1);
cell3 = cartrow.insertCell(2);
cell1.innerHTML= equipmentName;
cell2.innerHTML = equipmentPrice;
cell3.innerHTML = "<button class='btn btn-danger'>Delete</button>";
// Open Api information
var xhr = new XMLHttpRequest();
xhr.open('GET', 'pricing/orders/' + username +'/api', true);
xhr.onload = function(){
var data = JSON.parse(this.response);
cartBadge.innerHTML = data.length
if(xhr.status >= 200 && xhr.status < 400){
for(x in data){
for(y in data[x]){
array.push(Number(data[x][y]));
sum+=Number(data[x][y]);
subtotal.innerHTML = sum;
}
}
}else{
console.log(error);
}
}
xhr.send();
}
Flask Route routes.py
#app.route('/pricing/orders/<user_name>/api', methods=['POST', 'GET'])
#login_required
def api(user_name):
user_name = current_user.username
if request.method == 'POST':
cart.append(json.loads(request.form["javascript_data"]))
return jsonify(cart)
#app.route('/pricing/orders/delete', methods=['POST', 'GET'])
#login_required
def delete_item():
if request.method == 'POST':
print(cart[json.loads(request.form["delete_item"])])
cart.pop(json.loads(request.form["delete_item"]))
print(cart)
return jsonify({"whoa": "there"})
I'm a noob so this may be quite the long winded question an easy problem. Thanks guys!
You can try to bind event listener not to every single row (like you do in the loop), but for all of them in one time. After for loop add something like code below and remove event-listener in the loop, hope it will work:
document.querySelectorAll('.row-selector').on('click', function() {
... // do stuff with row
})
This problem can be solved using flask's context_processor. You can read more about it in official documentation. In a word you can put badge length in template's context and then use it anywhere in your templates, for example:
#app.context_processor
def inject_badge_length()
badge_length = ... // calculate badge length for current user
return {'BADGE_LENGTH': badge_length}
and then you can use it in template like:
<div class="badge-length">{{ BADGE_LENGTH }}</div>
Finally, if you have badge length (which can also be 0) you can hide subtotal html using css and javascript, like this:
#cart {
opacity: 0;
}
#cart.active {
opacity: 1;
}
and in js append this to the deleterow event-function (which, by the way, can be anonymous (nameless) function in this case):
if (cartBadge.innerHTML === "0") {
cart.classList.remove('active');
}
and somewhere in the end of 'addCartItem' function append:
if (!cart.classList.contains('active') && cartBadge.innerHTML !== "0") {
cart.classList.add('active');
}
I have a program that simply add's students to a table and stores that information into local-storage. I can add students and see the data stored into local-storage, but my big problem is figuring out how to remove a specific object within local storage upon button click after adding it (without clearing all of local storage).
Link for test: https://www.chriscaldwelldev.com/studentIA/student.html
Here is the table and inputs (HTML):
<body>
<div class="container">
<h1 class="title">Student Manager</h1>
<div class="controlCenter">
<table id="studentTable" class="table">
<thead>
<tr>
<th>Student Number:</th>
<th>Name:</th>
<th>Address:</th>
<th>Phone Number:</th>
<th>GPA:</th>
<th>Academic Plan:</th>
<th>Level:</th>
<th>Status:</th>
</tr>
</thead>
<tbody id="students"></tbody>
<tbody>
<tr>
<td><input type="text" id="studentN"></td>
<td><input type="text" id="name"></td>
<td><input type="text" id="address"></td>
<td><input type="text" id="phoneN"></td>
<td><input type="text" id="gpa"></td>
<td><input type="text" id="ap"></td>
<td><select id="selectL" name="SelectL">
<option value="" disabled selected>Select...</option>
<option value="freshman">Freshman</option>
<option value="sophomore">Sophomore</option>
<option value="junior">Junior</option>
<option value="senior">Senior</option>
<option value="graduate">Graduate</option>
</select></td>
<td><select id="selectS" name="SelectS">
<option value="" disabled selected>Select...</option>
<option value="active">Active</option>
<option value="inactive">Inactive</option>
</select></td>
</tr>
</tbody>
</table>
<input id="add" class="addButton" value="ADD">
</div>
</div>
</body>
Here is the JS:
// when the document loads
$(function(){
// add an onclick function to the id=add button
$("#add").click(function(){
var studentN = $("#studentN").val();
var name = $("#name").val();
var address = $("#address").val();
var phoneN = $("#phoneN").val();
var gpa = $("#gpa").val();
var ap = $("#ap").val();
var selectL = $("#selectL").val();
var selectS = $("#selectS").val();
if(studentN==null || name==null || address==null || phoneN==null ||
gpa==null || ap==null || selectL==null || selectS==null){
alert("All Fields Are Required to Add a Student");
return;
}
//create JSON object with text inputs with key:value pairs
var student = {
studentN: studentN,
name: name,
address: address,
phoneN: phoneN,
gpa: gpa,
ap: ap,
selectL: selectL,
selectS: selectS
}
//load local storage
var students = JSON.parse(localStorage.getItem("students"));
//if empty
if(!students){
students = [];
}
students.push(student);
localStorage.setItem("students", JSON.stringify(students));
// store a copy of the row in the body
var row = $("<tr>");
// store a copy of the current state in the <td> tag
var studentNData = $("<td>");
// now change the innerHTML for that <td>
studentNData.html(studentN);
// append the new value to our row
row.append(studentNData);
(...)
// store a copy of the current state for the next <td> tag
var selectSData = $("<td>");
// change the inner html of the <td>
selectSData.html(selectS);
// append the new value to our row
row.append(selectSData);
var deleteButton = $("<td>" + "<input type=\"button\" class=\"deleteButton\" value=\"X\">");
row.append(deleteButton);
// on the DOM, put the new row on the top of the list
$("#students").prepend(row);
// reset the values of the text inputs to empty strings
$("#studentN").val("");
$("#name").val("");
$("#address").val("");
$("#phoneN").val("");
$("#gpa").val("");
$("#ap").val("");
$("#selectL").val("");
$("#selectS").val("");
});
var students = JSON.parse(localStorage.getItem("students"));
$("#studentTable").on('click', '.deleteButton', function () {
$(this).closest('tr').remove();
//I can't think of what to do here...
});
if (students) {
// loop through the entire JSON array stored in local storage
for (i in students) {
// get a current copy of the content in the row
var row = $("<tr>");
// store a copy of the current state in the <td> tag, update the innerHTML, then append it to the DOM at the end of the row
var studentNData = $("<td>");
studentNData.html(students[i].studentN);
row.append(studentNData);
(...)
var selectSData = $("<td>");
selectSData.html(students[i].selectS);
row.append(selectSData);
var deleteButton = $("<td>" + "<input type=\"button\" class=\"deleteButton\" value=\"X\">");
row.append(deleteButton);
// now add the row to the DOM at the beginning of the list
$("#students").prepend(row);
}
}
});
I assume that whatever I need to do primarily needs to be done in the deleteButton onclick. I've thought some ideas through but they seem super wrong. I appreciate any help if you can.
One solution you could use is adding a data-studentn attribute to your delete buttons. Then, when the delete button is clicked, you can load the students array from localStorage, remove the student with that studentn, and save the new students array.
Change
"<input type=\"button\" class=\"deleteButton\" value=\"X\">"
to
"<input type=\"button\" class=\"deleteButton\" value=\"X\" data-studentn=\"" + students[i].studentN + "\" >"
Note: Remember to do something similar in the other place where you create a delete button.
Under //I can't think of what to do here... you can do the following:
var deletedStudentN = $(this).attr('data-studentn');
var students = JSON.parse(localStorage.getItem("students"));
students = students.filter(function(student) {
return student.studentN != deletedStudentN;
});
localStorage.setItem("students", JSON.stringify(students));
I want to be able to email content such as a div that is in my webpage using the php mail function and possible putting it on the so called "Thank Your, Your Email Sent" page. However, I'm running into some issues. I am following this Email Div Content, Email div text content using PHP mail function, and GET entire div with its elements and send it with php mail function questions that has already been posted as a guide but it doesn't seem to be working for me. I want to send via email and show up on the "Thank Your, Your Email Sent" page within the message. Anything I'm doing wrong?
HTML Table that I want to send over is:
<div id="add_items_content" style="width:100%;">
<center>
<table id="add_item_here" style="width:98%;">
<tbody>
<tr><td>Item</td><td>Years</td><td>Quantity</td><td>Training Hours</td><td>Total Item Cost</td></tr>
</tbody>
</table>
</center>
<center>
<table id="add_totals_here" style="width:98%;">
<tbody>
<tr><td cospan="3"> </td><td> </td><td> </td></tr>
</tbody>
</table>
</center>
</div>
<script>
$(document).ready(function(){
$('table[id^=add_item_here]').hide();
$('table[id^=add_totals_here]').hide();
$('div[id^=office_submit]').hide();
$('div[id^=show_form]').hide();
//First obtaining indexes for each checkbox that is checked
$('input[name=item_chk]').change(function(){
var index = this.id.replace('item_chk','');
if($(this).is(':checked')){
AddNewItem(index);
}else{
RemoveItem(index);
}
CalculateTotals();
});
function AddNewItem(index){
// Get hidden variables to use for calculation and tables.
var item = $('#item_chk'+index).parent().text().trim();
var itemdescr = $('#itemdescr'+index).val();
var traininghrs = parseInt($('#traininghrs'+index).val());
var qty = parseInt($('#qty'+index).val());
var yrs = parseInt($('#yrs'+index).val());
var item_cost = 0;
// Calculating item cost for just that one checkbox
item_cost+=parseInt($('#servicefee'+index).val());
item_cost*=parseInt($('#yrs'+index).val());
item_cost+=parseInt($('#licensefee'+index).val());
item_cost*=parseInt($('#qty'+index).val());
var traininghrs = parseInt($('#traininghrs'+index).val());
//Display each item that is checked into a table
$('#add_item_here tr:last').after('<tr id="row_id'+index + '"><td style=\"width:35%;\">' + itemdescr +'</td><td style=\"width:15%;\" >' + yrs +'</td><td style=\"width:16%;\">' + qty +'</td><td style=\"width:18%;\">' + traininghrs + '</td><td style=\"width:16%;\">$'+ item_cost + '</td></tr>');
}
function RemoveItem(index){
$('table#add_item_here tr#row_id'+index).remove();
}
function CalculateTotals(){
var total_cost = 0;
var total_training = 0;
$('input:checkbox:checked').each(function(){
var index = this.id.replace('item_chk','');
var item_cost = 0;
// Calculating item cost for just that one checkbox
item_cost+=parseInt($('#servicefee'+index).val());
item_cost*=parseInt($('#yrs'+index).val());
item_cost+=parseInt($('#licensefee'+index).val());
item_cost*=parseInt($('#qty'+index).val());
var traininghrs = parseInt($('#traininghrs'+index).val());
total_cost +=item_cost;
total_training +=traininghrs;
});
if(total_cost > 0 || total_training > 0) {
$('#add_totals_here tr:last').children().remove();
$('#add_totals_here tr:last').after('<tr ><td colspan="3" style=\"width:66%;\">TOTALS:</td><td style=\"width:18%;\">' + total_training + '</td><td style=\"width:16%;\">$'+ total_cost + '</td></tr>');
$('#add_item_here').show();
$('#add_totals_here').show();
$('#office_submit').show();
}else{
$('table[id^=add_item_here]').hide();
$('table[id^=add_totals_here]').hide();
$('div[id^=office_submit]').hide();
}
}
$("input[name='office_submit']").click(function () {
$('#show_form').css('display', ($(this).val() === 'Yes') ? 'block':'none');
});
// Quantity change, if someone changes the quantity
$('select[name=qty]').change(function(){
var index = this.id.replace('qty','');
if($("#item_chk"+index).is(':checked')){
RemoveItem(index);
AddNewItem(index);
CalculateTotals();
}
});
// Years change, if someone changes the years
$('select[name=yrs]').change(function(){
var index = this.id.replace('yrs','');
if($("#item_chk"+index).is(':checked')){
RemoveItem(index);
AddNewItem(index);
CalculateTotals();
}
});
})
</script>
Trial Number 1; So far I have tried:
<script>
function mail_content() {
var tablesContent = document.getElementById("add_items_content").innerHTML;
$.post('send_form.email.php',{content:tablecontent},function(data) {
});
}
</script>
Using script I have added to the send_form_email.php:
<?php
$txt = $_POST['content'];
mail($to,$subject,$message,$txt,$headers);
mail($from,$subject2,$message2,$txt,$headers2);
?>
Trial Number 2: I even tried storing it into a hidden field:
<input name="data" id="data" type="hidden" value=""></input>
<script type="text/javascript">
$(document).ready(function(){
$("#price_quote").submit(function() { //notice submit event
$("#my_hidden_field").val($("#add_items_content").html()); //notice html function instead of text();
});
});
</script>
And then the send_form_email.php I put it in that message see if it even shows up.
$txt = $_POST['data'];
$message = "Content: ".$txt."\n";
mail($to,$subject,$message,$txt,$headers);
mail($from,$subject2,$message2,$txt,$headers2);
Trial Number 3: Even tried Ajax
<script>
function mail_content(){
var html = $('#add_items_content').html();
$.ajax(function{
type="POST",
url:"send_form_email.php",
data:"data="+html,
success:function(response){
$('#add_items_content').show().html("email sent");
}
});
}
</script>
What am I missing or doing wrong? Why doesn't the div / tables show up or display?
You really should check your JS console for errors:
var tablesContent = document.getElementById("add_items_content").innerHTML;
^---note the "sC"
$.post('send_form.email.php',{content:tablecontent},function(data) {
^--note the c
JS vars are case sensitive, and will NOT magically correct typos for you.
And then there's this:
<input name="data" id="data" type="hidden" value=""></input>
^---id 'data'
$("#my_hidden_field").val($("#add_items_content").html());
^--- completely DIFFERENT ID
I want to get each cell value from an HTML table using JavaScript when pressing submit button.
How to get HTML table cell values?
To get the text from this cell-
<table>
<tr id="somerow">
<td>some text</td>
</tr>
</table>
You can use this -
var Row = document.getElementById("somerow");
var Cells = Row.getElementsByTagName("td");
alert(Cells[0].innerText);
function Vcount() {
var modify = document.getElementById("C_name1").value;
var oTable = document.getElementById('dataTable');
var i;
var rowLength = oTable.rows.length;
for (i = 1; i < rowLength; i++) {
var oCells = oTable.rows.item(i).cells;
if (modify == oCells[0].firstChild.data) {
document.getElementById("Error").innerHTML = " * duplicate value";
return false;
break;
}
}
var table = document.getElementById("someTableID");
var totalRows = document.getElementById("someTableID").rows.length;
var totalCol = 3; // enter the number of columns in the table minus 1 (first column is 0 not 1)
//To display all values
for (var x = 0; x <= totalRows; x++)
{
for (var y = 0; y <= totalCol; y++)
{
alert(table.rows[x].cells[y].innerHTML;
}
}
//To display a single cell value enter in the row number and column number under rows and cells below:
var firstCell = table.rows[0].cells[0].innerHTML;
alert(firstCell);
//Note: if you use <th> this will be row 0, so your data will start at row 1 col 0
You can also use the DOM way to obtain the cell value:
Cells[0].firstChild.data
Read more on that in my post at http://js-code.blogspot.com/2009/03/how-to-change-html-table-cell-value.html
You can get cell value with JS even when click on the cell:
.......................
<head>
<title>Search students by courses/professors</title>
<script type="text/javascript">
function ChangeColor(tableRow, highLight)
{
if (highLight){
tableRow.style.backgroundColor = '00CCCC';
}
else{
tableRow.style.backgroundColor = 'white';
}
}
function DoNav(theUrl)
{
document.location.href = theUrl;
}
</script>
</head>
<body>
<table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">
<% for (Course cs : courses){ %>
<tr onmouseover="ChangeColor(this, true);"
onmouseout="ChangeColor(this, false);"
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');">
<td name = "title" align = "center"><%= cs.getTitle() %></td>
</tr>
<%}%>
........................
</body>
I wrote the HTML table in JSP.
Course is is a type. For example Course cs, cs= object of type Course which had 2 attributes: id, title.
courses is an ArrayList of Course objects.
The HTML table displays all the courses titles in each cell. So the table has 1 column only:
Course1
Course2
Course3
......
Taking aside:
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');"
This means that after user selects a table cell, for example "Course2", the title of the course- "Course2" will travel to the page where the URL is directing the user: http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp . "Course2" will arrive in FoundS.jsp page. The identifier of "Course2" is courseId. To declare the variable courseId, in which CourseX will be kept, you put a "?" after the URL and next to it the identifier.
I told you just in case you'll want to use it because I searched a lot for it and I found questions like mine. But now I found out from teacher so I post where people asked.
The example is working.I've seen.
Just simply.. #sometime when larger table we can't add the id to each tr
<table>
<tr>
<td>some text</td>
<td>something</td>
</tr>
<tr>
<td>Hello</td>
<td>Hel</td>
</tr>
</table>
<script>
var cell = document.getElementsByTagName("td");
var i = 0;
while(cell[i] != undefined){
alert(cell[i].innerHTML); //do some alert for test
i++;
}//end while
</script>
<td class="virtualTd" onclick="putThis(this)">my td value </td>
function putThis(control) {
alert(control.innerText);
}
I found this as an easiest way to add row . The awesome thing about this is that it doesn't change the already present table contents even if it contains input elements .
row = `<tr><td><input type="text"></td></tr>`
$("#table_body tr:last").after(row) ;
Here #table_body is the id of the table body tag .
Here is perhaps the simplest way to obtain the value of a single cell.
document.querySelector("#table").children[0].children[r].children[c].innerText
where r is the row index and c is the column index
Therefore, to obtain all cell data and put it in a multi-dimensional array:
var tableData = [];
Array.from(document.querySelector("#table").children[0].children).forEach(function(tr){tableData.push(Array.from(tr.children).map(cell => cell.innerText))});
var cell = tableData[1][2];//2nd row, 3rd column
To access a specific cell's data in this multi-dimensional array, use the standard syntax: array[rowIndex][columnIndex].
Make a javascript function
function addSampleTextInInputBox(message) {
//set value in input box
document.getElementById('textInput').value = message + "";
//or show an alert
//window.alert(message);
}
Then simply call in your table row button click
<td class="center">
<a class="btn btn-success" onclick="addSampleTextInInputBox('<?php echo $row->message; ?>')" title="Add" data-toggle="tooltip" title="Add">
<span class="fa fa-plus"></span>
</a>
</td>