Unable to save input data from HTML table cells into JavaScript variables - javascript

I have tried to put input from a user into cells of a table, which was created using HTML and to save that data into a variable of JavaScript.
I was trying to get the data from rows cell of table to JavaScript variables one by one, but I'm getting undefined in place of data when alerting the data after summit.
HTML code
<table border = "2" cellpadding = "6" cellspacing = "6" bordercolor = "white" bgcolor = "red" class="center" id="mytable" >
<tr>
<th style="background: white;">EDUCATION</th>
<th style="background: white;">INSTITUTE</th>
<th style="background: white;">PERCENTAGE</th>
</tr>
<tr>
<td style="color: white;">10 th</td>
<td id="10inst"><input type="text"></td>
<td id="10per"><input type="text"></td>
</tr>
<tr>
<td style="color: white;" >12 th</td>
<td id="12inst"><input type="text"></td>
<td id="12per"><input type="text"></td>
</tr>
<tr>
<td style="color: white;">Graduaction</td>
<td id="gradinst"><input type="text"></td>
<td id="gradper"><input type="text"></td>
</tr>
<tr>
<td style="color: white;">Masters</td>
<td id="masterinst"><input type="text"></td>
<td id="masterper"><input type="text"></td>
</tr>
</table><br><br>
JavaScript code
var inst10 = document.getElementById("mytable").value;
var inst12 = document.getElementById("12inst").value;
var masterinst = document.getElementById("masterinst").value;
var per10 = document.getElementById("10per").value;
var per12 = document.getElementById("12per").value;
var masterper = document.getElementById("masterper").value;
var gradinst=document.getElementById("gradinst").value;
var gradper=document.getElementById("gradper").value;

There might be 2 problems in your code:
Make sure you run your JavaScript only after you enter text in the input elements.
You have <input> element inside <td> element. It means that when you getElementById of the <td> - you are not yet referencing the '' element. And the .value of '' is really undefined. So to fix that:
instead of
var inst12 = document.getElementById("12inst").value;
do:
var inst12 = document.getElementById("12inst").childNodes[0].value;
Full working example: https://jsfiddle.net/1dpg5j3q/

You must be add "id" attribute in input elements, not td elements or table elements
Like this;
<input id="12inst" type="text">

Related

How to get all values inside HTML table using JQuery

I have a table which looks like below and i want to get all values inside the table including the value of text box and check box.
<div class="container-fluid">
<h1 class="h3 mb-4 text-gray-800"><?= $title; ?></h1>
<div class="container" style="text-align: left">
<table class="table table-sm" id="tbl">
<thead>
<tr>
<th>No</th>
<th>Checklist Item</th>
<th>Cheklist</th>
<th>Actual</th>
<th>Recomended</th>
</tr>
</thead>
<tbody>
<tr>
<td scope="row">1</td>
<td>Check and clean rubber roller cage</td>
<td><input type="checkbox" name="chek" id="check"></td>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
<tr>
<td scope="row">2</td>
<td>Tension Rod all </td>
<td><input type="checkbox" name="chek" id="check"></td>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
<tr>
<td scope="row">3</td>
<td>Delete all unnecessary file from system</td>
<td><input type="checkbox" name="chek" id="check"></td>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
</table>
save
</div>
when i grab all value using this script i cant get value inside the text box and checkbox
$(document).on('click', '#save', function() {
var myRows = [];
var headersText = [];
var $headers = $("th");
// Loop through grabbing everything
var $rows = $("tbody tr").each(function(index) {
$cells = $(this).find("td");
myRows[index] = {};
$cells.each(function(cellIndex) {
// Set the header text
if (headersText[cellIndex] === undefined) {
headersText[cellIndex] = $($headers[cellIndex]).text();
}
// Update the row object with the header/cell combo
myRows[index][headersText[cellIndex]] = $(this).text();
});
});
var myObj = {
"Array": myRows
};
alert(JSON.stringify(myObj));
});
I want to convert it to JSON but the value of text box and check box not shows inside table. Kindly help me to resolve this issue.
Thank you in advance.
You can find the input and use .val() to get its value if the table cell's text is empty. Checkboxes and text inputs will need to be handled separately.
const text = $(this).text();
if(text){
myRows[index][headersText[cellIndex]] = text;
} else {
const input = $(this).find('input');
if(input.is(":checkbox")){
myRows[index][headersText[cellIndex]] = +input.prop('checked');
} else {
myRows[index][headersText[cellIndex]] = input.val();
}
}

Highlight multiple rows in several tables

I have a page with several rows containing information, made by several users. I'm looking for a way to highlight the all the users rows on mouseover.
This "Highlight multiple items on hover's condition" almost solved my problem, but since the classes or id's in my problem are dynamic from a database, and would contain an identifier from the DB and are unique each time. I have not been able to apply it.
Example code: https://jsfiddle.net/3cehoh78/
<table class="testtable">
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 1a</td>
<td class="cellclass">Sam</td>
<td class="cellclass">data</td>
</tr>
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 2a</td>
<td class="cellclass">Frodo</td>
<td class="cellclass">data</td>
</tr>
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 3a</td>
<td class="cellclass">Sam</td>
<td class="cellclass">data</td>
</tr>
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 4a</td>
<td class="cellclass">Legoman</td>
<td class="cellclass">data</td>
</tr>
</table>
<br>
<br>
<table class="testtable">
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 1b</td>
<td class="cellclass">Sauron</td>
<td class="cellclass">data</td>
</tr>
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 2b</td>
<td class="cellclass">Sam</td>
<td class="cellclass">data</td>
</tr>
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 3b</td>
<td class="cellclass">Sam</td>
<td class="cellclass">data</td>
</tr>
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 4b</td>
<td class="cellclass">Legoman</td>
<td class="cellclass">data</td>
</tr>
<tr id="uniqueIDthatcantbechanged">
<td class="cellclass">Line 5b</td>
<td class="cellclass">Frodo</td>
<td class="cellclass">data</td>
</tr>
</table>
In this example, I want all the rows with "Sam" to be highlighted on mouseover on one of them, so rows 1a,3a,2b,3b.
I was thinking of adding a class to all the Sam rows when generating the tables (Sam has a unique user ID), but how do I then change css that affects all the rows on mouseover (and not just one).
Please note that I cant pre-add css classes for all the unique userID's, this is just an example.
Here a solution with JQuery https://jsfiddle.net/3cehoh78/5
$(document).ready(function() {
$( "tr" ).hover(function() {
var search = $(this).find("td:eq(1)").text();
$( ".highlight" ).removeClass("highlight");
$("tr:contains('"+search+"')").addClass("highlight");
}); /* END HOVER */
}); // end document ready
Simple solution without using jQuery and co: https://jsfiddle.net/3cehoh78/3/
var rows = [].slice.call(document.querySelectorAll('.testtable tr'));
rows.forEach(function(row) {
row.addEventListener('mouseover', function() {
resetHighlighting();
var name = row.querySelector('td:nth-child(2)').textContent;
rows.forEach(function(r) {
if (r.querySelector('td:nth-child(2)').textContent === name) {
r.classList.add('highlighted');
}
});
});
});
function resetHighlighting() {
rows.forEach(function(row) {
row.classList.remove('highlighted');
});
}
Here's another way using vanilla-JavaScript.
var tds = document.querySelectorAll('td');
var highlight = function () {
// take this person's name from the 2nd cell
var name = this.parentNode.children[1].innerHTML;
// highlight cells with same name
tds.forEach(function (td) {
var tr = td.parentNode;
// compare other's person name with this person name
// highlight if there is a match
tr.classList.toggle('highlight', tr.children[1].innerHTML === name)
});
}
// attach an event listener to all cells
tds.forEach(function (td) {
td.onmouseover = highlight;
});
Demo

Change the TD value inside a particular Div Tag inside using jQuery

I have the following HTML Table,
<table id="items">
<tr class="total_up">
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line">Total</td>
<td class="total-value" id="total"><div id="totalone">$875.00</div></td>
</tr>
<tr class="disc" id="disc">
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line">Discount</td>
<td class="total-value" id="discount"><div id="discountid"><input type="text" name="disco" class="dis"/></div> </td>
</tr>
<tr class="tax_up">
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line balance">tax</td>
<td class="total-value" id="tax"><div id="tax">00</div></td>
</tr>
</table>
When i click on the button with id Discount, I need to change the value to the TD inside the div Tag with id "total" and set its value to another JavaScript variable?I tried the following, but it's not working.
$(".discountbtn").click(function(){
var test=$("#items #disc .dis").val(); //Easiest method
console.log("lol");
console.log(test);
var tot = roundNumber(test,2);
var new_tot=window.finale-tot;
console.log(window.finale);
console.log(new_tot);
$('#items #totalone').html("$"+new_tot);
//alert("button");
});
Try with my code that help you
change HTML <div id="totalone">$875.00</div> to $<span id="totalone">875.00</span>
$(document).ready(function() {
$("#discountbtn").click(function(){
var test=$("#items #disc .dis").val();
console.log(test);
var oldTotal = $("#totalone").text();
console.log(oldTotal);
var tot = Math.round(test * 100) / 100;
var new_tot=parseFloat(oldTotal)-tot;
console.log(new_tot);
$('#items #total').html(new_tot); //It was a jQuery selector glitch.
});
});
$('#items #totalone').html("$"+new_tot);

Copy data between specific <td> tags using jquery

I've a table like this:
<table>
<tr>
<td class="type">Order</td>
<td class="orderid">1002</td>
<td><button class="copy">Copy Row</button></td>
</tr>
<tr>
<td class="type">Order</td>
<td class="orderid">1004</td>
<td><button class="copy">Copy Row</button></td>
</tr>
<tr>
<td class="type">Refund</td>
<td class="orderid">1004</td>
<td><button class="copy">Copy Row</button></td>
</tr>
</table>
I've a script to copy data from a particular "#id" or ".class" element. What, I needed is to find a way to get the data of that particular row whenever, the Copy button is pressed. I want the columns 'orderid' and 'type' values of that particular row to be copied, but I'm not able to find a way to extract the data between the <td> tags with same class names.
Simple answer:
$('.copy').click(function(){
var order_id = $(this).parent().parent().find('.orderid').text();
var type = $(this).parent().parent().find('.type').text();
alert(order_id); ///this wil get you the value
});
I made the result here: http://codepad.viper-7.com/ahsVfB
check it.
<tr>
<td class="type">Refund</td>
<td class="orderid">1004</td>
<button class="copy">Copy Row</td>
</tr>
$(".copy").click(
function(event)
{
var copy=($(event.target).parent().find('.type'));
var order=($(event.target).parent().find('.orderid'));
}
);
You must paste that copied date somewhere. Make this copy and order as global variables. When you click paste, use this variable's value
take a look on this fiddle http://jsfiddle.net/3p29x2s9/11/
var buttons=document.getElementsByClassName("copy");
console.log(buttons);
for(var i=0;i<buttons.length;i++){
buttons[i].onclick=function(){
var columns = this.parentElement.parentElement.getElementsByTagName("td");
var type= columns[0].innerText;
var orderid=columns[1].innerText;
alert(type + " "+orderid);
}
}

incrementing the value of a input field in the cloned row

1)here i'm doing clone of a row...but this code is working only in eclipse [ ie ,cloning is working ] and it is also not working in any browsers.
2)What is the solution to get the values of text boxes in the cloned rows having same name, and insert into the database using jsp and servlet?
how can i get those values with same name
3)i have servlet code to get only single value from jsp
String address_seq_num =request.getParameter("address_seq_num");
how can i get the value of address seq number in the cloned row fromjsp to servlet to insert into the next row of a table in the database.
4)if i mention "DOCUMENT TYPE" to this code ,it will not work in eclipse also.....
please guide me...
JavaScript
function clonetable() {
var x=document.getElementById("main_table"); //get the table
var rowCount = x.rows.length;
var row = document.getElementById("table_row_clone"); // find row to copy
var table = document.getElementById("table_body"); // find table to append to
var clone = row.cloneNode(true); // copy children too
var tb1 = clone.document.getElementById("asn");//here i'm incrementing the value
tb1.value=rowCount+1;//of "address seq num " in the cloned row
clone.id = "abc"; // change id or other attributes/contents
table.appendChild(clone); // add new row to end of table
}
function deltable() {
var x = document.getElementById("main_table"); //get the table
var rowCount = x.rows.length;
if (rowCount > 1) {
x.deleteRow(rowCount - 1);
} //delete the last row
}
HTML
<table id="main_table" align="center" style="width:75%">
<tbody id="table_body">
<tr id="table_row_clone">
<td>
<table align="center" style="width:100%">
<tr>
<td align="center">
<div style="border:3px solid silver;border-radius:5px;background-color:grey">
<table width="100%">
<tr>
<th align="center">Address Details</th>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td>
<div style="border:3px solid silver;border-radius:5px;background-color:#1E90FF">
<table align="center" style="width:99%">
<tr style="background-color:#1E90FF">
<td style="width:35%">
<table width="100%">
<tr id="slrow">
<td style="width:43%">Address Seq Num</td>
<td>
<input id="asn" style="width:60px" name="address_seq_num" type="text" value="1" readonly>
</td>
</tr>
</table>
</td>
<td width="49%" align="right">
<input style="width:80%" type="text" value="Reg.office/Primary Office">
</td>
<td align="right">
<input style="width:30px" type="button" value="+" onclick="clonetable()">
<input style="width:30px" type="button" value="-" onclick="deltable()">
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</td>
</tr>
</tbody>
Per your HTML (which is messy, by the way) you can increment that textbox's value with something like:
var tb = document.getElementById("asn");
tb.value = parseInt(tb.value, 10) + 1;
The trick is you have to cast the textbox's value into a number, which is what parseInt is doing in that example.
Note that the above snippet will give you "NaN" in the textbox if the value is not a valid number - it's not doing any data validation at all.

Categories