Get the values from an array - javascript

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.

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);
}

Retrieving values from input elements in a table in HTML

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());
});

Get form values through JavaScript

This is my HJTML code. I don't know how to get values stored in filtertime[] using JavaScript and make them show on my screen.
<form action="index.php" method="post" >
<div class="col-lg-6"><div class="f-txt-l"><input id="test" type="checkbox" name="filtertime[]" class="morning" value="Morning"></div> <div class="f-txt-r">Morning</div></div>
<div class="col-lg-6"><div class="f-txt-l"><input id="test" type="checkbox" name="filtertime[]" class="morning" value="Afternoon"></div> <div class="f-txt-r">Afternoon</div></div>
<div class="col-lg-6"><div class="f-txt-l"><input id="test" type="checkbox" name="filtertime[]" class="morning" value="Evening"></div> <div class="f-txt-r">Evening</div></div>
<div class="col-lg-6"><div class="f-txt-l"><input id="test" type="checkbox" name="filtertime[]" class="morning" value="Night"></div> <div class="f-txt-r">Night</div></div>
<div class="col-lg-12"><input type="submit" name="button" class="apply-filter" value="Apply Filter"></div>
</form>
<script>
var new = document.getElementsById("test").innerhtml
</script>
How can I get input values in JavaScript through value is stored in array as filtertime[]?
try
in your form
<form action="index.php" id="myform" method="post" >
in jQuery
var datastring = $("#myform").serialize();
By JS
var params = '';
for( var i=0; i<document.FormName.elements.length; i++ )
{
var fieldName = document.FormName.elements[i].name;
var fieldValue = document.FormName.elements[i].value;
// use the fields, put them in a array, etc.
// or, add them to a key-value pair strings,
// as in regular POST
params += fieldName + '=' + fieldValue + '&';
}
Add id in your form tag.
<form action="index.php" id="form_name" method="post" >
Use below code to get all form element by JS :-
document.forms["form_name"].getElementsByTagName("input");
Note:- Above Code will work only if you don't have selects or textareas in your form.
If you have assigned id in DOM element like below,
<input type="text" name="name" id="uniqueID" value="value" />
Then you can access it via below code:-
Javascript:-
var nameValue = document.getElementById("uniqueID").value;
If you have Radio button in your form, then use below code:-
<input type="radio" name="radio_name" value="1" > 1
<input type="radio" name="radio_name" value="0" > 0<br>
Javascript:-
var radios = document.getElementsByName('radio_name');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
// do whatever you want with the checked radio
alert(radios[i].value);
// only one radio can be logically checked, don't check the rest
break;
}
}
Hope it will help you :)
this is the easiest way to get array of your form items
var arrValues = [];
for (var x =0; x < document.getElementsByClassName("morning").length ; x++)
{
arrValues.push(document.getElementsByClassName("morning")[x].checked);
}
To do that, the easiest way is to select all input with the "morning" class and after, foreach look if is checked :
var item = document.getElementsByClassName("morning"); // get all checkbox
var checkboxesChecked = []; // result array with ckecked ckeckbox
for (var i=0; i<item.length; i++) {
// if is checked add the value into the array
if (item[i].checked) {
checkboxesChecked.push(item[i].value);
}
}
console.log(checkboxesChecked);
In the "checkboxesChecked" array you have all the values of the checked box.

echo five times a input with jQuery

How is repeated code HTML for five times?
like repeated(echo) a input <input type="text" name="ok"> with a js code five times.
I mean this is that, a input by a js code echo five times
I want after run jQuery code output is this (5 input):
<input type="text" name="ok">
<input type="text" name="ok">
<input type="text" name="ok">
<input type="text" name="ok">
<input type="text" name="ok">
how is it?
Your question isn't totally clear, do you mean this?
for (var i = 0; i<5;i++) {
$("body").append("<input type='text' name='ok'>");
}
function EchoInput(html, count) {
var result = [];
for (var i = 0; i < count; i++)
result.push(html);
return result.join("");
}
To use this function, you could do something like this:
document.write(EchoInput("<input type='text' name='ok'>", 5));
var body = $('body');
for(var i = 0; i < 5; i++) {
body.append('<input type="text" name="ok">');
}
http://jsfiddle.net/ucbsh/1/
Instead of creating HTML, you can create elements directly.
Here is a way that let you set different names on each input field. Right now all five have the name "ok", but you can change that in the array:
// use ready event so that the page is loaded:
$(document).ready(function(){
// decide where to add the elements:
var container = $('body');
// loop over an array of names:
$.each(['ok','ok','ok','ok','ok'], function(idx, name) {
// create an element and add to the container:
container.append($('<input/>', { type: "text", name: name }));
});
});

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