Retrieving values from input elements in a table in HTML - javascript

I have a table set up as such:
<table id="mantab" style="cursor:pointer;" onkeypress="scan(event)">
<tr>
<td><input type='text' placeholder="Term" id='inp1' class="inp1" /></td>
<td><input type='text' placeholder="Definition" id='inp2' class="inp2" /></td>
</tr>
</table>
An action can be taken to add a row to this table, which is done by inserting a cell via the insertCell method and setting that cell's innerHTML appropriately.
What I've been trying to do is iterate through the first column of the table and add up all the values from inputs in each cell (after they've been entered) in a comma separated string. This process should be repeated for the second column.
The problem:
Everything I attempt to read is undefined
I've tried the following approaches to retrieving the contents of a cell:
document.getElementById("id").value,
document.getElementByClassName("classname").value,
table.rows[0].cells[0].value,
table.rows[0].cells[0].val(),
table.rows[0].cells[0].innerHTML,
table.rows[0].cells[0].children[0].val()
None work, some return blank, most undefined. The innerHTML one returns the input element inside the cell, but there is no actual text input data.
If a clearer picture of what I'm looking at is needed, see the following:
This should return one variable containing a string: "KeyA,KeyB,KeyC" and another with: "ValueA,ValueB,ValueC"
I'm somewhat new to javascript, but I have a basic knowledge of a couple other languages. I'm not sure why iterating through a table is posing such a challenge. Any help clarifying how I can extract these "invisible" values would be appreciated. Thanks.
Here is one of many approaches that isn't working for me:
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
if(j == 0) { //if first column
words += col.getElementsByClassName("inp1").value + ","; //inp1 refers to first column input class name
} else {
defs += col.getElementsByClassName("inp2").value + ","; //inp2 refers to second column input class name
}
}
}
In this example, words is analagous to the first variable from the image above, and defs to the second.
Update: logging the values and the element responsible for providing the values resulted in this:
The first log is blank, and the second has no value assigned, even though I typed in something.

You can do something like this using jQuery selectors
$("#bt").click(function()
{
var keys = [], values = [];
$('table tr input').each(function(i,e){
//access the input's value like this:
var $e = $(e);
if($e.hasClass('key')){
keys.push($e.val());
}else{
values.push($e.val());
}
});
keys = keys.join(',');
values = values.join(',');
console.log(keys);
console.log(values);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mantab" style="cursor:pointer;">
<tr>
<td><input type='text' placeholder="Term" id='inp1' class="key" /></td>
<td><input type='text' placeholder="Definition" id='inp2' class="value" /></td>
</tr>
<tr>
<td><input type='text' placeholder="Term" id='inp1' class="key" /></td>
<td><input type='text' placeholder="Definition" id='inp2' class="value" /></td>
</tr>
</table>
<button id="bt">
Get Value
</button>

what about using jQuery and finding all inputs in a table:
$('table input').each(function(i,e){
//access the input's value like this:
console.log($(e).val());
});

Related

how to dynamically increment input control by JavaScript....?

I used for loop to copy the table to n times. The code below works only in first table. How can i get to work in all tables?. I am a beginner.
function copy() {
var text1 = document.getElementById("Name1").value;
document.getElementById("Name2").value = text1;
var text2 = document.getElementById("Name3").value;
document.getElementById("Name4").value = text2;
}
<td rowspan="3" style="height:100px;">Name <input type="text" name="Emp name" placeholder="enter your name" id="Name1" /><br> ID <input type="id" name="Emp Id" placeholder="enter id" id="Name3"> </td>
<tr id="p001">
<td colspan="10" style="border:1px solid #ffffff;height:150px;"><input type="button" value="Get data" onclick="copy();" /><label for="text"> Name : <input type="text" id="Name2"></label>
<label for="text"> ID : <input type="id" id="Name4"></label> </td>
</tr>
ID's should always be unique. When using duplicate ID's it will only work on the first one and ignore the rest. By pushing in the selector to the function you can reuse your function for multiple tables.
https://jsfiddle.net/m5aqdswe/
onclick="copy('Name');"
function copy(selector) {
var text1 = document.getElementById(selector + "1").value;
document.getElementById(selector + "2").value = text1;
var text2 = document.getElementById(selector + "3").value;
document.getElementById(selector + "4").value = text2;
}
Hope this helps
EDIT TO HELP WITH YOUR FIDDLE MISTAKE
After checking your code I can see that you haven't implemented my fix. You have an onclick on the button calling copy();. You're not passing in any arguments so your JS is static. So when you add another table you're creating duplicate ID's.
When searching for an ID document.getElementById("Name1") it will search through the DOM until it finds that first id="Name1" and then stop. That is why your second table never works.
To fix that we need to push in your ID name to the function so that the JS becomes dynamic. copy('Name') where "Name" is the first part of your ID. The numbers will still be used.
In the function you need to grab that arguments by passing it in to the function and calling it whatever you like. I chose 'selector' because it is most descriptive. onclick="copy(selector)"
No the function will replace all the 'selector' variables with the string you passed through, namely "Name" so document.getElementById(selector + "1") will actually be document.getElementById("Name1"). This way you can create as many clones as you like but remember to change the clone table ID's and pass in the correct argument to the onclick.
Here is your fixed fiddle. https://jsfiddle.net/3shjhu98/2/
Please don't just copy, go see what I did. You'll need to fix your clone function to use dynamic arguments instead of static ones.
function check() {
var rowCount = $('table.mytable tbody tr');
for (var index = 0; index < rowCount.length; index++) {
var tr = $('table.mytable tbody tr')[index];
var td = $(tr).find('td');
for (var j = 0; j < rowCount.length; j++) {
copy('table.mytable tbody tr[data-index=' + index + '] td[data-index=' + j + ']');
}
}
}
function copy(selector) {
var val_1 = $(selector).find('input:first').val();
$(selector).find('input:last').val(val_1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table class="mytable">
<tbody>
<tr data-index="0">
<td data-index="0">
<input type="text" onblur="check()" />
<input type="text" />
</td>
</tr>
</tbody>
</table>
Hi. try it...
I think you need to pass table selector like [ table.className ] etc. then you find input text box and get the value this and paste into another text box.
Like this.
///it mean you pass first table row of first table data.
copy('table.className tbody tr[data-index=1] td[data-index=1]');
function copy(selector) {
var val_1 = $(selector).find('input#Name1').val();
$(selector).find('input#Name2').val(val_1);
}

How to calculate each table row indipendently on keyup

<tbody id="dailysale_tbody">
<tr class="items">
<td><select id="items_select" name="dailysale[luitem_id]"><option value=""></option></select></td>
<td><select id="brands_select" name="dailysale[lubrand_id]"><option value=""></option></select></td>
<td><select id="models_select" name="dailysale[lumodel_id]"><option value=""></option></select></td>
<td><input class="texts" id="dailysale_qty" name="dailysale[qty]" type="text" /></td>
<td><input class="texts" id="dailysale_price" name="dailysale[price]" type="text" /></td>
<td><input class="texts" id="dailysale_total" name="dailysale[total]" type="text" /></td>
<td><input type="checkbox" class="delete_row"></td>
</tr>
$(function() {
$('#dailysale_qty, #dailysale_price').keyup(function() {
var last_item = $('.items').find('#dailysale_qty');
var qty = last_row.find('#dailysale_qty').val();
var price = last_row.find('#dailysale_price').val();
var sub_total = last_row.find('#dailysale_total');
var s_total = qty * price;
if (isNaN(s_total)) {
sub_total.val('0');
}
else
sub_total.val(s_total);
});
});
I am able to perform calculations on this row. However, when I dynamically add rows with jquery, calculations are not working on the other rows.
When the calculating function is bind a button onclick, everything works well. But not on input keyup as required. I want to perform calculations on the new added row with onkeyup on qty and price input fields.
Note than upon cloning, the ids are stripped of the current row and assigned to the new row for reference.
You probably not registering keyup function when you adding new row.
You should do :
$('#dailysale_qty, #dailysale_price').unbind('keyup').keyup( function(...
Every time you adding new row.
#Nosyara The suggested line of code isn't working. Here is how am adding new rows. The commented line is what you suggested.
$(function(){
$('#newitembtn').click(function(){
//$('#dailysale_qty, #dailysale_price').unbind('keyup').keyup(function() {
var last_row = $('#dailysale_tbody').find('tr:last');
var newrow = last_row.clone();
last_row.find('#items_select').removeAttr('id');
last_row.find('#brands_select').removeAttr('id');
last_row.find('#models_select').removeAttr('id');
last_row.find('#dailysale_qty').removeAttr('id');
last_row.find('#dailysale_price').removeAttr('id');
last_row.find('#dailysale_total').removeAttr('id');
newrow.find('#items_select').val('');
newrow.find('#brands_select').val('');
newrow.find('#models_select').val('');
newrow.find('#dailysale_qty').val('');
newrow.find('#dailysale_price').val('');
newrow.find('#dailysale_total').val('');
last_row.after(newrow);
});
});
});

Get the values from an array

I have a table in my jsp:
<table id="table">
<tr>
<th>Valor</th>
<th>Recompensa</th>
</tr>
<tr>
<td>
<input type="text" name="amount">
</td>
<td>
<input type="text" name="text">
</td>
</tr>
</table>
<input type="button" value="Send" onclick="send('table')"/>
I write something in the boxes, and press Send, and the send Javascript method is called.
Javascript send method, which iterates through rows and cells, and stores the values in an Array:
function send(tableID) {
var table = document.getElementById(tableID);
var array= new Array();
for (var i = 1;i<table.rows.length; i++){
var row = table.rows[i];
for (var j = 0;row.cells.length; j++){
alert("added to array: "+row.cells[j].innerHTML);
array.push(row.cells[j].innerHTML);
}
}
}
I am getting "<input name="amount" type="text">" in the alert. I have tried using row.cells[j].firstChild.innerHTML, receiving undefined.
What am I doing wrong? how could I get what the user writes in the textboxes?
PS: I'm using Firefox to test. Maybe a browser issue?
You can use:
alert("added to array: " + row.cells[j].getElementsByTagName('INPUT')[0].value);
jsFiddle Example: http://jsfiddle.net/4TjYH/
EDIT: By the way, the code you posted may have been stripped down for simplicity, but if it's your actual code you can really simplify it:
function send(tableID) {
var array = new Array(),
inputs = document.getElementById(tableID).getElementsByTagName('INPUT');
for (var i = 0; i < inputs.length; i++){
alert("added to array: " + inputs[i].value);
array.push(inputs[i].value);
}
}
In the second loop is an error:
for (var j = 0; j < row.cells.length; j++){
"j <" was missing. the same problem was in the answer of Gavin: here the edit fiddle: http://jsfiddle.net/h693g/2/
Well, if you just want what the user has typed in the textboxes, you can assign ids to each textbox and use getElementById():
<input type="text" name="amount" id="amount">
<input type="text" name="text" id="text">
var amount = document.getElementById("amount");
var text = document.getElementById("text");
Then just push those two values on your array:
array.push(amount.value);
array.push(text.value);
You can put this logic in a loop, looping through an array of element ids or something if you didn't want to write similar code over and over.

jQuery foreach checkbox checked in tr > first td

i want to iterate through the table rows and get the id and name of each checkbox checked in each tr in the first td and save it in a new Object() called values ex: values.id, values.name
Thanks
<table>
<tr>
<td>
<input id="1" type="checkbox" name="name1" checked="checked">
</td>
<td>
Some input control 1
</td>
</tr>
<tr>
<td>
<input id="2" type="checkbox" name="name2">
</td>
<td>
Some input control 2
</td>
</tr>
</table>
Working example
aRecord is an array of objects with each object containing both the name and ID of each checked checkbox found in the table.
$(document).ready(function() {
var aRecord = [];
$('#your_table input:checkbox:checked').each(function() {
var oChkBox = {};
oChkBox.name = $(this).attr('name');
oChkBox.id = $(this).attr('id');
aRecord.push(oChkBox);
});
var i = aRecord.length;
while (i--) {
alert("Name: "+ aRecord[i].name + " ID: "+ aRecord[i].id);
}
});
http://jsfiddle.net/tracyfu/r6RMV/
var values = {};
$('tr input:checked').each(function(i) {
values[i] = [];
values[i].push($(this).attr('id'));
values[i].push($(this).attr('name'));
});
Will produce:
values = { [1, 'name1'] }
I'm leaving this solution as-is, since you specifically said you wanted to store the values in an object named values, but without knowing what you're going to do with the data, I would store the values in an array instead...

Retrieving a form field hidden value thats located in table cell <td>

I have a table with a cell that contains a hidden input type. How do you go about accessing the value of this hidden input type?
HTML Table:
<table id = "tableId">
<tr>
<td>FirstName LastName</td>
<td><input type="hidden" value="userId" /><td>
</tr>
Javascript
var table= document.getElementById("tableId");
var tblTR = table.getElementsByTagName("tr");
for (var i = 0; i<tblTR.length; i ++) {
var tr = tblTR[i];
var tds = tr.getElementsByTagName("td");
console.debug(tds[0]); //gets the whole cell
console.debug(tds[1].innerHTML); //gets content of cell, but not the actual value of the hidden input
}
With the second console.debug statement, the value I'm looking for is "userId" and not
<input type="hidden" value="userId" />
From what I understand, a td element cannot have a value attribute, therefore I can't simply just do a tds[i].value;.
Alternatively, is there another approach that can be used to store this hidden value?
You need to walk to the input tag itself
hiddenInputs = tds[1].getElementsByTagName("input");
console.debug(hiddenInputs[0].value);
or have a unique name or unique id to it and then you can access it directly.
<td><input type="hidden" id="inp1" value="userId" /><td>
document.getElementById("inp1").value
<td><input type="hidden" name="inp1" value="userId" /><td>
document.forms[0].inp1.value
The following works:
var inputs = document.getElementsByTagName('input');
for (i=0; i<inputs.length; i++){
if (inputs[i].type == 'hidden'){
alert(inputs[i].value);
}
}
JS Fiddle demo.
I'd suggest assigning the inputs[i].value to a variable, or an array, though rather than simply alert()-ing it:
var inputs = document.getElementsByTagName('input');
var values;
for (i=0; i<inputs.length; i++){
if (inputs[i].type == 'hidden'){
values = inputs[i].value;
}
}
Give your input tag a name
example:
<input type="hidden" value="userId" name='userId'/>
Then you can access it:
<form ...name='theform'>
...
<input type="hidden" value="userId" name='userId'/>
...
</form>
The Javascript
var value = document.theform.userId.value;
this should do, you can ignore the table cells

Categories

Resources