can you submit a form with an array of text input? - javascript

i am dynamically building a page. This page needs to read information from input tags but it is dynamic. Should i set up stuff to be an array since i am looking at
I want to preserve datasets.
<script>
function adjustPilots(){
var pilots = $("#numPilots").val();
var info = '<td><table>'+
'<tr><td>Minumum Collateral</td><td colspan="2"><input type = "text" size = "10" maxLength = "6" /> to <input type = "text" size = "10" maxLength = "6" /></td></tr>'+
'<tr><td>Reward</td><td colspan="2"><input type = "text" size = "10" maxLength = "6" /> to <input type = "text" size = "10" maxLength = "6" /></td></tr>'+
'<tr><td>Volume</td><td colspan="2"><input type = "text" size = "10" maxLength = "7" /> to <input type = "text" size = "10" maxLength = "7" /></td></tr>'+
'<tr><td>Start: </td><td><input type = "text" name = "s" id = "s" class = "s" value autocomplete = "off"></td></tr>'+
'<tr><td>End: </td><td><input type = "text" name = "e" id = "e" class = "e" value autocomplete = "off"></td></tr>'+
'</table></td>';
for(var i = 0; i < Number(pilots); i++){
$("#pilotrow").append(info);
}
}
</script>
<body>
<form>
<table>
<tr><td>Number of Pilots</td><td colspan="2"><input id = "numPilots" type = "text" size="3" maxLength="3" onchange = 'adjustPilots()' /></td></tr>
<tr id = "pilotrow"></tr>
<tr><td><input type = "submit" name = "submit"></td></tr>
</table>
</form>
</body>
An option i was thinking was to just not use a form, and build it with javascript. Then make a JSON object and use AJAX to send it to the server. Is that a solid way of doing it, or is there a better idea?

There are at least 2 way to do that.
Without javascript, you cate a form with array of element like this
<input type="text" name="input[]"/>
<input type="text" name="input[]"/>
<input type="text" name="input[]"/>
<input type="text" name="input[]"/>
in php
$inputs = $_POST['input'];
for($inputs as $inp){
}
With ajax and jquery, you can just simply serialize your form and post to backend

You can achieve that by using the name attribute in your inputs. Like so:
<input type="text" name="pilots[]" />
Then you would probably want to keep track of how many pilots you are adding that way you can send an indexed array. Like so:
<input type="text" name="pilots[0][minumumCollatural]" />
<input type="text" name="pilots[0][reward]" />
<input type="text" name="pilots[0][volume]" />
That way when you submit your form to the server, your array of pilots will look something like:
$pilots = $_POST['pilots'];
// Which looks like
array(
[0] => array
(
[minumumCollatural] => // Some number
[reward] => // Some number
)
[1] => array
(
[minumumCollatural] => // Some number
[reward] => // Some number
)
)

Try utilizing the hidden input tag to send data in whatever fashion you please. For instance:
<input type="hidden" name="myinput" id="myinput" />
Now in JS:
$("form").submit(function() {
$("input").not("#myinput").each(function() {
$("#myinput").val($("#myinput").val()+$(this).val());
// you can format anyway you want this is just an example
});
});
Hope this helps!

Related

How can I access these form values?

I want to create a form where I will perform an operation with the values entered by the user, but when the function runs, I get NaN return. Thank you in advance for the help.
function test() {
var age = document.getElementsByName("person_age").value;
var weight = document.getElementsByName("person_weight").value;
var size = document.getElementsByName("person_size").value;
document.getElementById("result").innerHTML = weight + size + age;
}
<form>
<input type="text" name="person_age">
<input type="text" name="person_size">
<input type="text" name="person_weight">
<input type="button" value="calculate" onclick="test();">
</form>
<h3 id="result"></h3>`
Output:
NaN
When I get the values from the user and run the function, I get NaN feedback. how can i solve this problem.
There are multiple errors that you have to correct
1) When you use getElementsByName, It will return NodeList array like collection. So you have to get the element by using index as:
var age = document.getElementsByName( "person_age" )[0].value;
2) If you need sum of all three value then you have to convert it into Number type because document.getElementsByName( "person_age" )[0] give you value in String type. So you can do as:
+document.getElementsByName( "person_age" )[0].value
function test() {
var age = +document.getElementsByName("person_age")[0].value;
var size = +document.getElementsByName("person_size")[0].value;
var weight = +document.getElementsByName("person_weight")[0].value;
document.getElementById("result").innerHTML = weight + size + age;
}
<form>
<input type="text" name="person_age">
<input type="text" name="person_size">
<input type="text" name="person_weight">
<input type="button" value="calculate" onclick="test();">
</form>
<h3 id="result"></h3>
Just a Suggestion: You can use Document.getElementById if you want to directly access the value. Just add an ID property in your element. It will return a string value, convert that to int and you're good to go.
function test() {
var age = document.getElementById("person_age").value;
var weight = document.getElementById("person_weight").value;
var size = document.getElementById("person_size").value;
document.getElementById("result").innerHTML = parseInt(weight) + parseInt(size) + parseInt(age);
}
<form>
<input type="text" name="person_age" id="person_age">
<input type="text" name="person_size" id="person_size">
<input type="text" name="person_weight" id="person_weight">
<input type="button" value="calculate" onclick="test();">
</form>
<h3 id="result"></h3>
getElementsByName will always return an array-like nodelist so, if you were to use it you would need to access the first index [0]. Instead add a class to each input and use querySelector to target it.
The value of an input will always be a string (even if the input is type "number"), so you need to coerce it to a number, either by using Number or by prefixing the value with +.
So, in this example I've updated the HTML a little by adding classes to the inputs, and changing their type to "number", and removing the inline JS, and updated the JS so that the elements are cached outside of the function, an event listener is added to the button, and the values are correctly calculated.
// Cache all the elements using querySelector to target
// the classes, and add an event listener to the button
// that calls the function when it's clicked
const ageEl = document.querySelector('.age');
const weightEl = document.querySelector('.weight');
const sizeEl = document.querySelector('.size');
const result = document.querySelector('#result');
const button = document.querySelector('button');
button.addEventListener('click', test, false);
function test() {
// Coerce all the element values to numbers, and
// then display the result
const age = Number(ageEl.value);
const weight = Number(weightEl.value);
const size = Number(sizeEl.value);
// Use textContent rather than innerHTML
result.textContent = weight + size + age;
}
<form>
<input type="number" name="age" class="age" />
<input type="number" name="size" class="size" />
<input type="number" name="weight" class="weight" />
<button type="button">Calculate</button>
</form>
<h3 id="result"></h3>`

How to assign some value to input tag

I need to put some value to element.
Here is my code snippet.
var userId = localStorage.getItem('keyName');
var Name = document.getElementById('Name');
var dbRefName = firebase.database().ref().child('Web App').child('Users').child(userId).child('Name');
dbRefName.on('value', snap => Name.innerText = snap.val());
I am trying to assign this Name value using id to the input element shown as below.
<input type="text" id="Name" class="form-control form-control-alternative" placeholder="Username" >
It can assign using id to <span> elements. But it is not working with <input> elements.
Could anyone please help me on this matter?
Use .value instead of .innerText for <input> elements, like so:
document.getElementById('input').value = 'foo'
<input id="input"></input>
Input HTML elements needs name tag, and the way to assign it a value is by the value tag or by .value in Javascript
var input = document.getElementById('name');
//input.value = localStorage.getItem('keyName');
input.value = 5;
<input type="number" name="name" id="name" placeholder="Your name here" value="1">

Display sum of other inputs into another element with javascript

Question
How can I have an element dynamically display the sum of various inputs?
Background
I have several text boxes (with the same class). I have 4 inputs, each with a number. Input 1 is "1", 2 is "2", etc.
I want the fifth box to contain the sum of "1, 2, 3, 4".
Issue
I am struggling with the javascript.
Ideally the fourth box with id final would update as any of the previous boxes are edited.
Can I do it using the classes? that is my intent as the amount of inputs can vary, it will not always be four.
HTML
<input type='text' id='txtFirst' class='copyText' /><br/>
<input type='text' id='txtSecond' class='copyText' /><br/>
<input type='text' id='txtThird' class='copyText' /><br/>
<input type='text' id='final' />
$('.copyText').on('keyup', function(){
var val = 0;
$('.copyText').each(function(){
val = val + (+$(this).val());
})
$('#final').val(val);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type='text' id='txtFirst' class='copyText' /><br/>
<input type='text' id='txtSecond' class='copyText' /><br/>
<input type='text' id='txtThird' class='copyText' /><br/>
<input type='text' id='final' />
Try this which uses jQuery (demo using 2.1.0)
$('.copyText').on('keyup', function(){
var val = 0;
$('.copyText').each(function(){
val = val + (+$(this).val());
})
$('#final').val(val);
})
To see the the working demo click here. Or run the code snippet here.
window.onload = _ => {
//get the html elements
const texts = Array.from(document.getElementsByClassName("copyText"));
const out = document.getElementById("final");
//a function for getting all the text values and updating the ouput
function update(){
out.value = texts.map( text => text.value ).join(", ");
}
//await input, then update
texts.forEach( text => text.addEventListener("input", update) );
};
With jQuery get the fields values :
$('.copyText').map(function(){return $(this).val();})
Transform to string with :
.get().join(',')
And assign it to #final with :
$("#final").val();
Conclusion :
$("#final").val($('.copyText').map(function(){return $(this).val();}).get().join(','));

How to convert the input name dot to json format in simple way?

I have used the struts json plugin and tried to convert the form data to json format to submit by ajax.
I have two cases in the HTML
<form>
<input type="text" name="user.name" value="Tom"></p>
<input type="text" name="user.location" value="China"></p>
<input type="text" name="user.data[0].id" value="993"></p>
<input type="text" name="user.data[0].accountId" value="123"></p>
<input type="text" name="user.data[1].id" value="222"></p>
<input type="text" name="user.data[1].accountId" value="333"></p>
</form>
What I expected is to convert it to the json structure:
{
user : {
name: "Tom",
location : "China",
data: [
{
id : 993,
accountId : 123
},
{
id : 222,
accountId : 333
}
]
}
}
I know how to declare the json data and declare the attributes one by one.
I would like to have the better way to make each form to be in json format using simple way rather than declaring the parameter one by one in json format.
Appreciate for any suggestion or advice. Thank you.
Provided your form is exactly like that
Using a plain JS approach
<form class="userform">
<input type="text" class="username" value="Tom"></p>
<input type="text" class="userlocation" value="China"></p>
<input type="text" class="userid" value="993"></p>
<input type="text" class="useraccountid" value="123"></p>
<input type="text" class="userid2" value="222"></p>
<input type="text" class="useraccountid2" value="333"></p>
</form>
Then assign the values to the object
var frm = document.getElementsByClassName('userform');
//initialize blank object and keys
var user = {},
user.name = "",
user.location = "",
user.data = [];
//get all child input elements
for(var i = 0; i < frm.length; i++){
var uname = frm[i].getElementsByClassName('username')[0];
var uloc = frm[i].getElementsByClassName('userlocation')[0];
var uid = frm[i].getElementsByClassName('userid')[0];
var uaccid = frm[i].getElementsByClassName('useraccountid')[0];
var uid = frm[i].getElementsByClassName('userid2')[0];
var uaccid = frm[i].getElementsByClassName('useraccountid2')[0];
//assign values to object here
user[name] = {}; //assigning a parent property here, the name for example.
user[name].name = uname.value;
user[name].location = uloc.value;
user[name].data.push({
'id': uid.value
'accountId': uaccid.value
});
user[name].data.push({
'id': uid2.value
'accountId': uaccid2.value
});
}
JSON.stringify(user); //convert to JSON (or ignore if you want a plain object)
Output would be this in JSON format
{
user :{
Tom: {
name: "Tom",
data: [
{
id : 993,
accountId : 123
},
{
id : 222,
accountId : 333
}
]
},
Jerry: {
//more data
},
Courage: {
//more data
}
}
}
Hope this helps
If your input fields are many, like id3, accountid3, 4, 5, 6. You have to loop through the classes that you assign to these two repetitive fields
Here you go with a solution using jQuery https://jsfiddle.net/pnz8zrLx/2/
var json = {};
$('button').click(function(){
$('form').each(function(i){
json["user" + i] = {};
json["user" + i].data = [];
var tempJSON = {};
$('form:nth-child(' + (i+1) + ') input[type="text"]').each(function(){
if($(this).attr('name') === 'name' || $(this).attr('name') === 'location'){
json["user" + i][$(this).attr('name')] = $(this).val();
} else {
tempJSON[$(this).attr('name')] = $(this).val();
if(tempJSON != {} && $(this).attr('name') === 'accountId'){
json["user" + i].data.push(tempJSON);
tempJSON = {};
}
}
});
});
console.log(json);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="name" value="Tom">
<input type="text" name="location" value="China">
<input type="text" name="id" value="993">
<input type="text" name="accountId" value="123">
<input type="text" name="id" value="222">
<input type="text" name="accountId" value="333">
</form>
<form>
<input type="text" name="name" value="Test">
<input type="text" name="location" value="Test112">
<input type="text" name="id" value="22">
<input type="text" name="accountId" value="78">
<input type="text" name="id" value="00">
<input type="text" name="accountId" value="44">
</form>
<button>
Submit
</button>
Hope this will help you.

Print an array from user input in JavaScript

I am trying to create an array from user input in JavaScript and display the latest array as the numbers are appended to the array. The numbers are not getting printed.
Kindly help.
HTML part :
<textarea form = "arrays" cols = 10 rows = 2 id = "num">
</textarea><br />
<form id = "arrays" method = "" onsubmit="arrAppend(document.getElementById('num').value);">
<input type ="submit" value="Append" />
</form>
JavaScript part :
<script>
var myarr = [];
function arrAppend(num) {
myarr.push(+num);
text = "";
for (var x = 0; x< myarr.length; x++) {
text += myarr[x];
}
console.log(text);
}
</script>
This is working :
HTML :
<input type = "text"
id = "addNumber" />
<input type = "button"
id = "addToArray"
value = "Append"
onclick = "arrAppend();" />
JavaScript :
function arrAppend() {
myarr[x] = document.getElementById('addNumber').value;
alert("Element : "+myarr[x]+" is added at index "+x);
x++;
document.getElementById('addNumber').value = "";
<textarea form = "arrays" cols = 10 rows = 2 id = "num">
</textarea><br />
<input type ="submit" value="Append" onclick="arrAppend(document.getElementById('num').value);"/>
why do you need a form? are you submitting something to the server? when you submit a form it will clear the global array as well.

Categories

Resources