merge textbox values with javascript - javascript

I have 5 textbox in html. I want to merge their values. All of them have one name. How can I do it?
<input type="text" name="textbox1">
<input type="text" name="textbox1">
<input type="text" name="textbox1">
<input type="text" name="textbox1">
<input type="text" name="textbox1">

Get the values as an array, and join it
var val = [].map.call( document.getElementsByName('textbox1'), (el) => el.value ).join('');
var values = [].map.call( document.getElementsByName('textbox1'), (el) => el.value ).join('');
console.log(values)
<input type="text" name="textbox1" value="a1-">
<input type="text" name="textbox1" value="a2-">
<input type="text" name="textbox1" value="a3-">
<input type="text" name="textbox1" value="a4-">
<input type="text" name="textbox1" value="a5-">

If you want to select by the name attribute of your inputs, use getElementsByName like this:
var inputs = document.getElementsByName("textbox1");
var inputValues = "";
for(var index=0; index < inputs.length; index++) {
inputValues += inputs[index].value;
}

Related

set value array in all inputs with same tag class

I'm trying to do loop over all tag with same className and get their value:
var quantity = [];
$(".add_more_items").each(function(){
quantity.push($(this).val());
});
this is a result, for example:
['1', '9', '1']
but my problem is I'm trying to set value from this array to other input with same class:
$.each(quantity, function(index, val){
$(".items_final").val(val);
});
but always set in all inputs last value from my array, i donĀ“t know what I'm doing wrong.
Use an index assuming there is 1 to 1 mapping between the fields
const $final = $(".items_final");
$(".add_more_items").each(function(i, item) {
$final[i].value = item.value; // or $final.eq(i).val(item.value)
});
const $final = $(".items_final");
$(".add_more_items").each(function(i, item) {
$final[i].value = item.value; // or $final.eq(i).val(item.value)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Add more</h3>
<input type="text" value="1" class="add_more_items" />
<input type="text" value="2" class="add_more_items" />
<input type="text" value="3" class="add_more_items" />
<input type="text" value="4" class="add_more_items" />
<hr/>
<h3>final</h3>
<input type="text" value="" class="items_final" />
<input type="text" value="" class="items_final" />
<input type="text" value="" class="items_final" />
<input type="text" value="" class="items_final" />
Also this is useful:
const quantity = $(".add_more_items").map(function(){
return this.value; // or $(this).val()
}).get();

Computing using functions and arrays / Output error: Not a Number

Background: I'm practicing arrays and functions and am having trouble computing the sum of array items. I'm pretty sure there is something wrong with the function I'm writing but I'm not sure what. Using 8 input fields I'm pulling data into a array one item at a time and converted to floating numbers(for now...I'll try to fix that later). I've created a function that will compute the total of this list but it only outputs NaN.
Any suggestions are highly appreciated!
function myfunction() {
list = [];
list[0] = parseFloat(document.getElementById('number1').value);
list[1] = parseFloat(document.getElementById('number2').value);
list[2] = parseFloat(document.getElementById('number3').value);
list[3] = parseFloat(document.getElementById('number4').value);
list[4] = parseFloat(document.getElementById('number5').value);
list[5] = parseFloat(document.getElementById('number6').value);
list[6] = parseFloat(document.getElementById('number7').value);
list[7] = parseFloat(document.getElementById('number8').value);
function total(myvals) {
let total = 0;
for (let i = 0; i <= myvals.length; i++) {
total += myvals[i];
}
return total;
}
document.getElementById('results').innerHTML = total(list);
}
<form>
<input type="text" name="number1" id="number1"><br>
<input type="text" name="number2" id="number2"><br>
<input type="text" name="number3" id="number3"><br>
<input type="text" name="number4" id="number4"><br>
<input type="text" name="number5" id="number5"><br>
<input type="text" name="number6" id="number6"><br>
<input type="text" name="number7" id="number7"><br>
<input type="text" name="number8" id="number8"><br>
<input type="submit" value="Compute Score" onclick="javascript:myfunction()">
</form>
<div id="results"></div>
Here is a simple example using a for loop with querySelectorAll.
Additionally, I cleaned up your code a bit. Run the snippet below:
EDIT: Included some comments to show what's happening.
function myfunction() {
let total = 0;
//get the value for each element being called by querySelectorAll
//add values to total to get a sum
document.querySelectorAll('input').forEach(el => total += +el.value);
//append the new value to the results div
document.querySelector('#results').innerHTML = total;
}
<form>
<input type="text" name="number1" id="number1"><br>
<input type="text" name="number2" id="number2"><br>
<input type="text" name="number3" id="number3"><br>
<input type="text" name="number4" id="number4"><br>
<input type="text" name="number5" id="number5"><br>
<input type="text" name="number6" id="number6"><br>
<input type="text" name="number7" id="number7"><br>
<input type="text" name="number8" id="number8"><br>
</form>
<br/><br/>
<button type="submit" onclick="myfunction()">Compute Score</button>
<br/><br/>
<div id="results"></div>
This is resolved. I was able to fix my source code by removing
"<=" in the for loop and adding "<" in its place. Thanks everyone, I will look over everything else for extra practice!
1 - in HTML forms and their elements use names.
2 - each element of a form can be accessed by name with the form as parent
3 - if several elements have the same name (with the same type of preference) then they form an object collection
PS: I have used here [... myForm.numX] to transform the myForm.numX collection to array, so that it can accept the arry.map () method
this way:
const myForm = document.forms['my-form']
, res = document.getElementById('results')
;
myForm.onsubmit = evt =>
{
evt.preventDefault() // disable submit
let list = [...myForm.numX].map(inp => parseFloat(inp.value))
res.textContent = list.reduce((t,v)=>t+v,0)
// control...
console.clear()
console.log( myForm.numX.length, JSON.stringify(list) )
}
<form name="my-form">
<input type="text" name="numX" placeholder="num 1"><br>
<input type="text" name="numX" placeholder="num 2"><br>
<input type="text" name="numX" placeholder="num 3"><br>
<input type="text" name="numX" placeholder="num 4"><br>
<input type="text" name="numX" placeholder="num 5"><br>
<input type="text" name="numX" placeholder="num 6"><br>
<input type="text" name="numX" placeholder="num 7"><br>
<input type="text" name="numX" placeholder="num 8"><br>
<button type="submit">Compute Score</button>
</form>
<div id="results">..</div>

Generating secure random numbers for HTML form

I am trying to create a JS function to generate 6 random, secure numbers that are inputted in a HTML form. I currently have:
function secureRandomNums(len) {
let array = new Uint8Array(len);
window.crypto.getRandomValues(array);
return array;
}
function getRandomNumbers() {
let elements = form.getElementsByName("number[]");
let nums = secureRandomNums(elements.length);
for (let i = 0; i < nums.length; i++) {
elements[i].value = nums[i]
}
}
In the HTML file I am calling the getRandomNumbers here:
<form action="AddUserNumbers" id="add_numbers_form" method="post" class="forms">
<label for="number1">Number 1:</label><br>
<input type="text" id="number1" name="number[]"><br>
<label for="number2">Number 2:</label><br>
<input type="text" id="number2" name="number[]"><br>
<label for="number3">Number 3:</label><br>
<input type="text" id="number3" name="number[]"><br>
<label for="number4">Number 4:</label><br>
<input type="text" id="number4" name="number[]"><br>
<label for="number5">Number 5:</label><br>
<input type="text" id="number5" name="number[]"><br>
<label for="number6">Number 6:</label><br>
<input type="text" id="number6" name="number[]"><br>
<input type="button" value="Generate numbers!" onclick="getRandomNumbers()"><br>
<input type="submit" id="submit_numbers" value="Submit your numbers" form="add_numbers_form"><br>
</form>
But it is not displaying the values. What am I doing wrong?
I had it working with an implementation of the Math.random() function but this is not as secure as window.crypto.
getElementsByName() is a document level method and not available at element level
Use querySelectorAll() instead to query elements that only exist in the specific form
const form = document.forms[0]
function secureRandomNums(len) {
let array = new Uint8Array(len);
window.crypto.getRandomValues(array);
return array;
}
function getRandomNumbers() {
let elements = form.querySelectorAll('input[name="number[]"]');
let nums = secureRandomNums(elements.length);
for (let i = 0; i < nums.length; i++) {
elements[i].value = nums[i]
}
}
<form>
<input name="number[]" />
<input name="number[]" />
<input name="number[]" />
<input type="button" value="Generate numbers!" onclick="getRandomNumbers()"><br>
</form>

Trying to get all input value into string, jquery or javascript

I am trying to use jquery or javascript get all input value into a string (1,2,3,4) and ignore empty value. Thank you.
<form id="sym_form">
<input type="text" class="as_sym" id="sym_1" value="1">
<input type="text" class="as_sym" id="sym_2" value="2">
<input type="text" class="as_sym" id="sym_3" value="3">
<input type="text" class="as_sym" id="sym_4" value="4">
<input type="text" class="as_sym" id="sym_5" value="">
</form>
// string to keep the result
var output = "";
// iterate over all inputs with class 'as_sym' inside the '#sym_form'
$('#sym_form > input[class=as_sym]').each(function(){
// only inputs with non-empty values
if ($(this).val() != "") {
// the first value doesn't have a comma in front of it
// subsequent values do have a comma in front of them
if (output == "") {
output += $(this).val();
} else {
output += "," + $(this).val();
}
}
});
// here do whatever you want with the 'output' variable
const form = document.getELementById("sym_form");
for (var element of form.elements) {
if(element.nodeName === "INPUT" && element.value) {
// do something with element.value
}
}
var $inputs = $('#sym_form .as_sym');
var result ="";
$.each($inputs, function(i, v) {
var val = $(this).val();
result += val;
});
$('#result').text(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="sym_form">
<input type="text" class="as_sym" id="sym_1" value="1">
<input type="text" class="as_sym" id="sym_2" value="2">
<input type="text" class="as_sym" id="sym_3" value="3">
<input type="text" class="as_sym" id="sym_4" value="4">
<input type="text" class="as_sym" id="sym_5" value="">
</form>
<p id="result"></p>
You can use .querySelectorAll() to select all "#sym_form .as_sym" elements, Array.prototype.forEach(), Function.prototype.call() to attach input event to each element, at input event concantenate values of each "#sym_form .as_sym" element to a string, use .split(), .join() to include comma , character between each character or resulting string
var inputs = document.querySelectorAll("#sym_form .as_sym");
Array.prototype.forEach.call(inputs, function(input) {
input.addEventListener("input", function(e) {
for (var i = 0, val = "", len = inputs.length; i < len; i++) {
val += inputs[i].value;
}
console.log(val.split("").join(","))
})
})
<form id="sym_form">
<input type="text" class="as_sym" id="sym_1" value="1">
<input type="text" class="as_sym" id="sym_2" value="2">
<input type="text" class="as_sym" id="sym_3" value="3">
<input type="text" class="as_sym" id="sym_4" value="4">
<input type="text" class="as_sym" id="sym_5" value="">
</form>

how to concatenate two or more text box values in one text box

I want to concatenate two or more text box values in one text box.Here I am getting values using id but that id will be dynamically added it means text box will dynamically added.For dynamically adding text box I am using for loop but am getting the value only the last text box value only becaues for loop executed.I want all text box values.Please help me to get me out.Thank you in advance.
Here is the code for dynamic text box process:
In this am using printwriter object in servlet
int nums=5;
out.println("<input type='text' id='static'>");
int i;
for (i=0;i<nums; i++) {
out.println("<input type='text' Style='width:30px' maxlength='1' id='id"+i+"'onkeyup='sum();'> ");
out.println("<script>function sum(){ alert('id"+i+"'); var txtFirstNumberValue=document.getElementById('id'+i+'').value;var result = document.getElementById('static').value + txtFirstNumberValue;alert(result);if (isNaN(result)){ document.getElementById('static').value = result; }}</script>");
}
but if I use static text box I am getting what I need but I need that in dynamic process.
here is the code for static text box process:
<input type="text" maxlength="1" id="1" onkeyup="sum();"/>
<input type="text" maxlength="1" id="2" onkeyup="sum();"/>
<input type="text" maxlength="1" id="3" onkeyup="sum();"/>
<input type="text" id="4"/>
function sum() {
var txtFirstNumberValue = document.getElementById('1').value;
var txtSecondNumberValue = document.getElementById('2').value;
var txtThirdNumberValue = document.getElementById('3').value;
var result = txtFirstNumberValue + txtSecondNumberValue + txtThirdNumberValue;
if (isNaN(result)) {
document.getElementById('4').value = result;
}
}
Please help me to find out the solution.Thank you in advance.
I would not use inline JavaScript and I would give my elements proper IDs if I really need them otherwise I would use classes.
$(document).ready(function() {
$('.in').on('input',function() {
var allvals = $('.in').map(function() {
return this.value;
}).get().join('');
$('.out').val( allvals );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="in" type="text" maxlength="1" id="i1"/>
<input class="in" type="text" maxlength="1" id="i2"/>
<input class="in" type="text" maxlength="1" id="i3"/>
<input class="out" type="text" id="i4"/>
<script type="text/javascript">
$(document).ready(function(){
var cls = document.getElementsByClassName('test');
var i =0;
var len = cls.length;
var tot = 0;
for(i=0;i<l;i++){
var cur = cls[i].value;
tot = parseInt(cur)+tot;
}
//document.getElementById("id"+cls.length).value = tot; //set the value for last element as the tot var
});
</script>
<body>
<input type="text" maxlength="1" value="1" id="1" class="test"/>
<input type="text" maxlength="1" value="2" id="2" class="test"/>
<input type="text" maxlength="1" value="3" id="3" class="test"/>
</body>
$(document).ready(function() {
$('.in').on('input',function() {
var allvals = $('.in').map(function() { return this.value; }).get().join('');
$('.out').val( allvals );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="in" type="text" maxlength="1" id="i1"/>
<input class="in" type="text" maxlength="1" id="i2"/>
<input class="in" type="text" maxlength="1" id="i3"/>
<input class="out" type="text" id="i4"/>
$(document).ready(function() {
$('.in').on('input',function() {
var allvals = $('.in').map(function() {
return this.value;
}).get().join('');
$('.out').val( allvals );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="in" type="text" id="i1"/>
<input class="in" type="text" id="i2"/>
<input class="in" type="text" id="i3"/>
<input class="out" type="text" id="i4"/>

Categories