Get average value without filling all fields and without button - javascript

So I have 3 input boxes which I want to use it to make an average value from those boxes in a readonly input box without clicking any button (just by changing values).
Here is the html:
input1: <input name="1" id="1" value="" ><br>
input2: <input name="2" id="2" value="" ><br>
input3: <input name="3" id="3" value="" ><br><br>
output: <input name="output" id="4" value="" readonly>
And here is the script:
var input = $('[name="1"],[name="2"],[name="3"]'),
input1 = $('[name="1"]'),
input2 = $('[name="2"]'),
input3 = $('[name="3"]'),
input4 = $('[name="output"]');
input.change(function () {
var val1 = (isNaN(parseInt(input1.val()))) ? 0 : parseInt(input1.val());
var val2 = (isNaN(parseInt(input2.val()))) ? 0 : parseInt(input2.val());
var val3 = (isNaN(parseInt(input3.val()))) ? 0 : parseInt(input3.val());
input4.val((val1 + val2 + val3)/3);
});
However, I want to have the average value without filling all 3 input boxes and the divider is based on how many textboxes I input.
Like when I input value in textbox1 and textbox2, the output will be like (textbox1+textbox2)/2 rather than (textbox1+textbox2+0)/3.
I'm quite sure the problem is in "input4.val((val1 + val2 + val3)/3);" line.
But I can't figure out how to write the proper code

You can use input event instead of change. You can use filter() and map() to get the array of non-empty input. Then use reduce() to find the sum and finally divide that by the length of the array to get the result.
Try the following:
var input = $('[name="1"],[name="2"],[name="3"]'),
input1 = $('[name="1"]'),
input2 = $('[name="2"]'),
input3 = $('[name="3"]'),
input4 = $('[name="output"]');
input.on('input', function (el) {
var vArray = input.filter(function(i,el){
return !isNaN(this.value.trim()) && $(el).val().trim() != "";
}).map((j,k) => Number(k.value)).get();
var res = '';
if(vArray.length > 0)
res = vArray.reduce((a,c) => a+c,0)/vArray.length;
input4.val(res);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
input1: <input name="1" id="1" value=""><br>
input2: <input name="2" id="2" value="" ><br>
input3: <input name="3" id="3" value="" ><br><br>
output: <input name="output" id="4" value="" readonly>:

jQuery version
$('input.input').on('blur', function() {
let values = [];
$('input.input').each(function() {
let value = $(this).val();
if (value && !isNaN(value) && !(/^ *$/.test(value))) {
values.push(Number($(this).val()));
}
});
if (values.length) {
$('input.output').val(values.reduce(function(a, b) {
return a + b;
}) / values.length);
} else {
$('input.output').val('');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="inputs">
input1: <input class="input" name="1" id="1" value=""><br> input2: <input class="input" name="2" id="2" value=""><br> input3: <input class="input" name="3" id="3" value=""><br><br>
</div>
output: <input class="output" name="output" id="4" value="" readonly>

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

In this code, i want to add values by clicking the value buttons

I want to add values by clicking the value buttons by each and every by the following function
function sum() {
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var txtThirdNumberValue = document.getElementById('txt3').value;
var txtFourthNumberValue = document.getElementById('txt4').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
var result = parseInt(txtFirstNumberValue) + parseInt(txtThirdNumberValue);
var result = parseInt(txtFirstNumberValue) + parseInt(txtFourthNumberValue);
if (!isNaN(result)) {
document.getElementById('txt1').value = result;
}
}
// Here I gave the other two events to add to the text field by the id names
<!-- here I gave the three Value buttons and on click function -->
<input type="text" id="txt1" value="10" />
<input type="button" id="txt2" value="10" onClick="sum();" />
<input type="button" id="txt3" value="20" onClick="sum();" />
<input type="button" id="txt4" value="30" onClick="sum();" />
You can get the value of the button by passing this.value to the onClick function where this represent the element itself.
function sum(value) {
document.getElementById('txt1').value = Number(document.getElementById('txt1').value) + Number(value);
}
<input type="text" id="txt1" value="10" />
<input type="button" id="txt2" value="10" onClick="sum(this.value);" />
<input type="button" id="txt3" value="20" onClick="sum(this.value);" />
<input type="button" id="txt4" value="30" onClick="sum(this.value);" />
This javascript will help you.
<script>
function sum(e) {
var result = parseInt(e.value) + parseInt(document.getElementById('txt1').value);
if (!isNaN(result)) {
document.getElementById('txt1').value = result;
}
}
</script>

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"/>

return all values of input fields within div

I need to form a string with the all values input fields within a div layer - using jquery
<div id="selection">
<input class="field" id="1" type="hidden" value="A"/>
<input class="field" id="2" type="hidden" value="B"/>
<input class="field" id="3" type="hidden" value="C"/>
<input class="field" id="4" type="hidden" value="D"/>
</div>
<input type="button" id="button" value="generate"/>
in this form:
id[1]=val[A]&id[2]=val[b]...so on
jquery:
$(function() {
$('#button').click(function() {
//function goes here...
});
});
If you use name instead of (or in addition to) id:
<input class="field" name="1" type="hidden" value="A"/>
<input class="field" name="2" type="hidden" value="B"/>
<input class="field" name="3" type="hidden" value="C"/>
<input class="field" name="4" type="hidden" value="D"/>
you can use serialize:
$('#button').click(function() {
alert($('#selection input').serialize());
});
which gives you
1=A&2=B&3=C&4=D
If you really want to have the id[x] structure, you can give the elements the names id[1], id[2] etc.
Edit: Oh, somehow I overlooked that you want val[x] as well. This would not be possible with serialize, only if you really put val[x] as value in the fields. But why do you need such an obfuscated structure?
Btw. you are missing type="button" at your button.
<script>
$(function() {
$('#button').click(function() {
var str = new Array();
var count = 0;
$('.field').each(
function()
{
str[count] = 'id['+$(this).attr('id')+']=val['+$(this).val()+']';
count++;
}
);
alert(str.join('&'))
});
});
</script>
<div id="selection">
<input class="field" id="1" type="hidden" value="A"/>
<input class="field" id="2" type="hidden" value="B"/>
<input class="field" id="3" type="hidden" value="C"/>
<input class="field" id="4" type="hidden" value="D"/>
</div>
<input id="button" value="generate" type="button"/>
Another solution that gives the exact specified output and handles missing attributes gracefully:
See it in action at jsFiddle:
$(function() {
$('#button').click(function() {
var ResStr = $('#selection input.field');
ResStr = ResStr.map (function () {
var jThis = $(this);
var ID = jThis.attr ("id");
if (!ID) ID = "null";
var VAL = jThis.val ()
if (!VAL) VAL = "null";
return 'id[' + ID + ']=val[' + VAL + ']';
} ).get () .join ('&');
alert (ResStr);
} );
} );
this returns all the html combined of all the inputs inside the div
var h = '';
var c = 0;
$('#selection input.field').each(function(){
h += '&id['+(++c)+']=val['+$(this).val()+']';
});
h = h.slice(1);
alert(h);

Categories