Trying to get all input value into string, jquery or javascript - 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>

Related

Get average value without filling all fields and without button

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>

merge textbox values with 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;
}

How to calculate the total value of each section separately: Jquery

I have more than 10 section that included three inputs in each section as follows:
<div class="product_quantity">
<div class="color-quantity">
<input onkeydown="return myFunction(event);" name="custom_small" class="custom_small" type="text">
<input onkeydown="return myFunction(event);" name="custom_medium" class="custom_medium" type="text">
<input onkeydown="return myFunction(event);" name="custom_large" class="custom_large" type="text">
</div>
<div class="color-quantity">
<input onkeydown="return myFunction(event);" name="white_small" class="custom_small" type="text">
<input onkeydown="return myFunction(event);" name="white_medium" class="custom_medium" type="text">
<input onkeydown="return myFunction(event);" name="white_large" class="custom_large" type="text">
</div>
</div>
I am calculating the product quantity from each section but its giving me the whole amount of products on the basis of amount entered in every input. but i want the amount of products in section separately
I am using jQuery to do so please check the code and recommend the changes as required:
jQuery(".color-quantity input").each(function () {
if (this.value) {
quantity += (this.value) * 1;
classname = jQuery(this).attr('class');
arr.push(classname);
}
if (quantity == '') {
quantity = 0;
}
});
You can get total off each section as an array like following.
var arr = $('.color-quantity').map(function () {
var total = 0;
$('input', this).each(function () {
total += this.value * 1;
});
//do some stuff
if (total < 50) {
$('.btn-cart').removeAttr("onclick");
}
return total;
}).get();
console.log(arr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="color-quantity">
<input type="text" value="1">
<input type="text" value="2">
<input type="text" value="3">
</div>
<div class="color-quantity">
<input type="text" value="4">
<input type="text" value="5">
<input type="text" value="6">
</div>
You might try a nested loop. first loop through the color-quantity divs, then through the inputs. like this:
jQuery(".color-quantity").each(function () {
var quantity = 0;
$(this).find('input').each(function() {
if (this.value) {
quantity += (this.value) * 1;
classname = jQuery(this).attr('class');
arr.push(classname);
}
if (quantity == '') {
quantity = 0;
}
});
// here is where you can get the total value for each div
});

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