How to assign a javascript variable to input text field? - javascript

I've a variable called "numbers" in javascript and this variables holds 10 numbers from 0 to 9 as shown below.
var numbers = "0123456789";
Now what I want to be able to do is assigning each of these numbers to an input text field using document.getElementByID("a") = "";, for example:
<input type="text" id="a" value="" />
<input type="text" id="b" value="" />
<input type="text" id="c" value="" />
<input type="text" id="d" value="" />
<input type="text" id="e" value="" />
<input type="text" id="f" value="" />
<input type="text" id="g" value="" />
<input type="text" id="h" value="" />
<input type="text" id="i" value="" />
<input type="text" id="j" value="" />
Currently the following text fields above holding no values, but I want to be able to assign each of the numbers in variable "numbers" to each of the text fields above, so it would looks like this when user clicks on a button called click me.
<input type="text" id="a" value="0" />
<input type="text" id="b" value="1" />
<input type="text" id="c" value="2" />
<input type="text" id="d" value="3" />
<input type="text" id="e" value="4" />
<input type="text" id="f" value="5" />
<input type="text" id="g" value="6" />
<input type="text" id="h" value="7" />
<input type="text" id="i" value="8" />
<input type="text" id="j" value="9" />
Also is there any way to leave a text field empty if a particular number is = 0
Thanks in advance :)

var numbers = "0123456789";
var ids = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"];
for (var i = 0; i < ids.length; i++)
{
var el = document.getElementById(ids[i]);
var num = numbers[i];
if (num == "0")
el.value = "";
else
el.value = num;
}
Working sample: http://jsfiddle.net/LrJ5S/.

In addition to mellamokb, another way of accomplishing the same:
var numbers = "abc0123abc0123";
var inputs = document.getElementsByTagName('input');
var i = 0;
for(var s = 0; s < inputs.length; s++) {
inputs[s].value = numbers.charAt(i)!=0?numbers.charAt(i):'';
i++;
}
JSFiddle

Basic example with no checks on data size of inputs and string:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title></title>
</head>
<body>
<div id="myInputs">
<input type="text" id="a" value="" />
<input type="text" id="b" value="" />
<input type="text" id="c" value="" />
<input type="text" id="d" value="" />
<input type="text" id="e" value="" />
<input type="text" id="f" value="" />
<input type="text" id="g" value="" />
<input type="text" id="h" value="" />
<input type="text" id="i" value="" />
<input type="text" id="j" value="" />
</div>
<button id="run">Run</button>
<script type="text/javascript">
function putNumbers(){
var numbers = "0123456789";
var inputs = document.getElementById("myInputs").getElementsByTagName("input");
for(var i=0;i<inputs.length;i++){
var val = numbers.charAt(i);
inputs[i].value = val==="0"?"":val;
}
}
document.getElementById("run").onclick = putNumbers;
</script>
</body>
</html>
working Example

Related

How to loop through text fields and concatenate the result using javascript

I need to write a javascript function that will loop through the input boxes and concatenates the text in each field together and displays the result in the result box. I tried multiple solutions and haven't been able to get any to work, I get that it needs an array of text fields but I can't seem to work it out.
<!DOCTYPE html>
<html>
<body>
<form id="myform">
<label for="text1">text1</label><br>
<input type="text" id="text1" name="text1"><br>
<label for="text2">text2</label><br>
<input type="text" id="text2" name="text2"><br>
<label for="text3">text3</label><br>
<input type="text" id="text3" name="text3"><br>
<label for="text4">text4</label><br>
<input type="text" id="text4" name="text4"><br>
<label for="text5">text5</label><br>
<input type="text" id="text5" name="text5"><br>
<label for="text6">text6</label><br>
<input type="text" id="text6" name="text6"><br>
<input type="button" onClick="myFunction()" value="Click This"><br>
<label for="result">result</label><br>
<input type="text" id="result" name="result">
</form>
<script>
function myFunction() {
var fields = [];
}
</script>
</body>
</html>
You can use filter and map
NOTE: I gave the button an ID of "btn"
document.getElementById('btn').addEventListener('click', function() {
const conc = [...document.querySelectorAll('#myform [id^=text]')] // id starts with text
.filter(fld => fld.value.trim() !== "") // not empty
.map(fld => fld.value) // store value
document.getElementById('result').value = conc.join(","); // join with comma
})
<form id="myform">
<label for="text1">text1</label><br>
<input type="text" id="text1" name="text1"><br>
<label for="text2">text2</label><br>
<input type="text" id="text2" name="text2"><br>
<label for="text3">text3</label><br>
<input type="text" id="text3" name="text3"><br>
<label for="text4">text4</label><br>
<input type="text" id="text4" name="text4"><br>
<label for="text5">text5</label><br>
<input type="text" id="text5" name="text5"><br>
<label for="text6">text6</label><br>
<input type="text" id="text6" name="text6"><br>
<input type="button" id="btn" value="Click This"><br>
<label for="result">result</label><br>
<input type="text" id="result" name="result">
</form>
In one pass:
document.getElementById('btn').addEventListener('click', function() {
const res = [];
[...document.querySelectorAll('#myform [id^=text]')]
.forEach(fld => { const val = fld.value.trim(); if (val !== "") res.push(val) })
document.getElementById('result').value = res.join(","); // join with comma
})
<form id="myform">
<label for="text1">text1</label><br>
<input type="text" id="text1" name="text1"><br>
<label for="text2">text2</label><br>
<input type="text" id="text2" name="text2"><br>
<label for="text3">text3</label><br>
<input type="text" id="text3" name="text3"><br>
<label for="text4">text4</label><br>
<input type="text" id="text4" name="text4"><br>
<label for="text5">text5</label><br>
<input type="text" id="text5" name="text5"><br>
<label for="text6">text6</label><br>
<input type="text" id="text6" name="text6"><br>
<input type="button" id="btn" value="Click This"><br>
<label for="result">result</label><br>
<input type="text" id="result" name="result">
</form>
function myFunction() {
const data = document.querySelectorAll("#myform input[type='text'][id^=text]");
//console.log(data);
var fields = [];
data.forEach(item => {
if (item.value != '') {
fields.push(item.value)
}
})
document.getElementById("result").value = fields.join(",")
}
<form id="myform">
<label for="text1">text1</label><br>
<input type="text" id="text1" name="text1"><br>
<label for="text2">text2</label><br>
<input type="text" id="text2" name="text2"><br>
<label for="text3">text3</label><br>
<input type="text" id="text3" name="text3"><br>
<label for="text4">text4</label><br>
<input type="text" id="text4" name="text4"><br>
<label for="text5">text5</label><br>
<input type="text" id="text5" name="text5"><br>
<label for="text6">text6</label><br>
<input type="text" id="text6" name="text6"><br>
<input type="button" onClick="myFunction()" value="Click This"><br>
<label for="result">result</label><br>
<input type="text" id="result" name="result">
</form>

Sum the values of the inputs of a specific form and display the result

My page is made of several forms with several inputs called "values[]".
When modifying these inputs in one of the forms, I would like to sum the values and display the result in an other input of the same form called "total".
My html code looks like that:
<form action="index.php" method="post" id="form_1">
<input type="text" name="values[]" id="value_1_1" onkeyup="sum_values(this)" />
<input type="text" name="values[]" id="value_1_2" onkeyup="sum_values(this)" />
[... More inputs with the name "values[]" ]
<input type="text" name="total" disabled>
</form>
<form action="index.php" method="post" id="form_2">
<input type="text" name="values[]" id="value_2_1" onkeyup="sum_values(this)" />
<input type="text" name="values[]" id="value_2_2" onkeyup="sum_values(this)" />
[... More inputs with the name "values[]" ]
<input type="text" name="total" disabled>
</form>
and my javascript is :
<script type="text/javascript">
function sum_values(x){
var arr = document.getElementById(x.form.id).elements['values[]'];
var tot=0;
for(var i=0;i<arr.length;i++)
{
if(parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById(x.form.id).elements['total'].value = tot;
}
</script>
I was very happy to finally see the first form working, but I then figured out that the second one was not...
Could you help me to understand why ?
I'm a beginner at javascript and I tried to arrange some code I found.
Thank you very much
If you'd like to get all elements within a specific form, you can do so using code similar to the following. The rest of your code should work fine, except your final result input selector.
var formId = 'form1';
var arr = document.querySelectorAll('#' + formId + ' [name="values[]"]');
var tot=0;
for(var i=0; i<arr.length; i++) {
if(parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.querySelector('#' + formId + ' [name="total"]').value = tot;
<form id="form1">
<input type="text" name="values[]" value="5" />
<input type="text" name="values[]" value="1" />
<input type="text" name="values[]" value="6" />
<input type="text" name="values[]" value="8" />
<input type="text" name="values[]" value="2" />
<input type="text" name="values[]" value="0" />
<input type="text" name="values[]" value="1" />
<input type="text" name="values[]" value="3" />
<input type="text" name="total" disabled>
</form>

Round off all computed textbox decimal places into 2

Hi I am having a problem with my script, I want to round of all the result on text boxes simultaneously every changes that I am making on every textboxes.
I am talking about hundreds of textboxes that will round off after every changes/input on textboxes.
Anyways here is my sample code of my work.
HTML:
<input type="text" id="textbox" value="1.1251112314555" />
<br/>
<input type="text" id="textbox2" value="1" />
<br/>
<input type="text" id="textbox3" value="1" readonly/>
<br/>
<input type="text" id="textbox4" value="1" readonly/>
<br/>
Javascript:
$("input[type=text]").blur(function() {
totalad3 = parseInt(textbox) * parseInt(textbox2);
totalad4 = parseInt(textbox) + parseInt(textbox2);
$('#textbox3').val(totalad3);
$('#textbox4').val(totalad4+"%");
var num = parseFloat($("input[type=text]").val());
var new_num = $("input[type=text]").val(num.toFixed(2));
});
if you want to update values in each input with rounded values on blur event of any input, in the handler function get all the inputs and then iterate over each input and change its value. something like this:
$('input[type=text]').on('blur', function() {
var inputs = $('input[type=text]');
inputs.each(function(){
var num = parseFloat($(this).val());
var new_num = num.toFixed(2);
$(this).val(new_num);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textbox" value="1.1251112314555" />
<br/>
<input type="text" id="textbox2" value="1" />
<br/>
<input type="text" id="textbox3" value="1" readonly/>
<br/>
<input type="text" id="textbox4" value="1" readonly/>
<br/>
<input type="button" id="calculate" value="Calculate"/>
hundreds of textboxes that will round off after every changes/input on
textboxes.
If I understand your requirement correctly..
$("input[type=text]").blur(function() {
// console.log("Which textbox has changes?", $(this).val() );
// Get current input value
var currentInputValue = parseFloat($(this).val());
// Round them to 2 decimal
var roundedValue = currentInputValue.toFixed(2);
// Update back to textbox
$(this).val( roundedValue );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textbox" value="1.1251112314555" />
<br/>
<input type="text" id="textbox2" value="1" />
<br/>
<input type="text" id="textbox3" value="1" readonly/>
<br/>
<input type="text" id="textbox4" value="1" readonly/>
<br/>
<input type="text" id="textbox5" value="123.2323" />
<br/>
<input type="text" id="textbox6" value="1.444" />
<br/>
<input type="text" id="textbox7" value="23.23235" />
<br/>
<input type="button" id="calculate" value="Calculate"/>
Another way using Array.from with Map function.
<script type="text/javascript">
$(function () {
$("input[type=text]").on('blur', function(){
Array.from($("input[type=text]"), (el, i) => $(el).val(parseFloat($(el).val()).toFixed(2)));
})
});
</script>
<input type="text" id="textbox" value="1.1251112314555" />
<br/>
<input type="text" id="textbox2" value="1" />
<br/>
<input type="text" id="textbox3" value="1" readonly/>
<br/>
<input type="text" id="textbox4" value="1" readonly/>
<br/>
<input type="button" id="calculate" value="Calculate" />

How to get data-attribute value of elements which is greater than given value using jquery?

I have few textboxes and data-attrribute for installment number.
<input type="text" id="54" data-instno="12"/>
<input type="text" id="124" data-instno="13"/>
<input type="text" id="88" data-instno="14"/>
<input type="text" id="126" data-instno="15"/>
<input type="text" id="102" data-instno="16"/>
<input type="text" id="8" data-instno="17"/>
<input type="text" id="87" data-instno="18"/>
<input type="text" id="112" data-instno="19"/>
If my installment number is 15. i want to get controls have data-instno>=15. that means last 5 textboxes in this case.
Use jQuery Has Attribute Selector [name] to selecting target elements and use .filter() to filtering element has data-instno great than 15.
$("[data-instno]").filter(function(){
return $(this).attr("data-instno") >= 15;
}).doSomething();
$("[data-instno]").filter(function(){
return $(this).attr("data-instno") >= 15;
}).css("background", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="54" data-instno="12"/>
<input type="text" id="124" data-instno="13"/>
<input type="text" id="88" data-instno="14"/>
<input type="text" id="126" data-instno="15"/>
<input type="text" id="102" data-instno="16"/>
<input type="text" id="8" data-instno="17"/>
<input type="text" id="87" data-instno="18"/>
<input type="text" id="112" data-instno="19"/>
If you want to get value of data-instno use this
var arr = $("[data-instno]").map(function(){
return $(this).attr("data-instno");
}).get().filter(function(value){
return value >= 15;
});
var arr = $("[data-instno]").map(function(){
return $(this).attr("data-instno");
}).get().filter(function(value){
return value >= 15;
});
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="54" data-instno="12"/>
<input type="text" id="124" data-instno="13"/>
<input type="text" id="88" data-instno="14"/>
<input type="text" id="126" data-instno="15"/>
<input type="text" id="102" data-instno="16"/>
<input type="text" id="8" data-instno="17"/>
<input type="text" id="87" data-instno="18"/>
<input type="text" id="112" data-instno="19"/>
Just plain JavaScript:
console.log(
[].filter.call(document.getElementsByTagName('INPUT'),
function(elem) {
return elem.dataset.instno >= 15;
})
);
<input type="text" id="54" data-instno="12"/>
<input type="text" id="124" data-instno="13"/>
<input type="text" id="88" data-instno="14"/>
<input type="text" id="126" data-instno="15"/>
<input type="text" id="102" data-instno="16"/>
<input type="text" id="8" data-instno="17"/>
<input type="text" id="87" data-instno="18"/>
<input type="text" id="112" data-instno="19"/>
var arrNumber = new Array();
$('input[type=text]').each(function(){
if($(this).attr('data-instno') >= 15){
arrNumber.push($(this).attr('data-instno'));
}
});
use this you will get this as an array

number increment button

I have an existing html form which use array to store multiple row values. So I do not have a specific name for the same field for different row. In the PHP page i match the row according to the index.
In the form below, how do I make the button + and - to increase and decrease the value of the quantity of the specific row?
ROW 1
<input type="text" name="product[]" />
<input type="text" name="price[]" value="" onChange="updatePrice()" />
<input type="text" name="quantity[]" value="" onChange="updatePrice()" />
<input type="button" onclick="inc(this)" value="+"/>
<input type="button" onclick="dec(this)" value="-"/>`
ROW 2
<input type="text" name="product[]" />
<input type="text" name="price[]" value="" onChange="updatePrice()" />
<input type="text" name="quantity[]" value="" onChange="updatePrice()" />
<input type="button" onclick="inc(this)" value="+"/>
<input type="button" onclick="dec(this)" value="-"/>
ROW 3
<input type="text" name="product[]" />
<input type="text" name="price[]" value="" onChange="updatePrice()" />
<input type="text" name="quantity[]" value="" onChange="updatePrice()" />
<input type="button" onclick="inc(this)" value="+"/>
<input type="button" onclick="dec(this)" value="-"/>
In my opinion you first should to numerate items:
<input type="text" name="product[]" />
<input id="price-1" type="text" name="price[]" value="" onChange="updatePrice(1)" /> <!-- row number -->
<input id="qty-1" type="text" name="quantity[]" value="" onChange="updatePrice(1)" />
<input type="button" onclick="inc('qty-1')" value="+"/>
<input type="button" onclick="dec('qty-1')" value="-"/>
Then use javascript to manipulate items:
<script>
function inc(id) {
stepQty(id, +1);
}
function dec(id) {
stepQty(id, -1);
}
function stepQty(id, step) {
var value = $('#'+id).val();
$('#'+id).val(value + step);
}
function updatePrice(id) {
var a = $('#price-'+id).val() || 0;
var b = $('#qty-'+id).val() || 0;
$('#'+id).val(a*b);
}
</script>

Categories

Resources