I have a form with multiple input fields:
<input name="a1"/>
<input name="a2"/>
<input name="a3"/>
All field names are the same with an added digit.
I need JavaScript to read these values into an array.
for i = 1 to 3
a(i) = form(i)
next
Complete code:
var listC = [ "C", "A", "B" ];
a1 = form.a1.value;
a2 = form.a2.value;
a3 = form.a3.value;
if (listC[0] == a1.toUpperCase()) {
NumCorrect = NumCorrect + 1
}
if (listC[1] == a2.toUpperCase()) {
NumCorrect = NumCorrect + 1
}
if (listC[2] == a3.toUpperCase()) {
NumCorrect = NumCorrect + 1
}
<input type="text" size="2" name="a1" size="2"/>
<input type="text" size="2" name="a2" size="2"/>
<input type="text" size="2" name="a3" size="2"/>
Not sure if this is what you're after.
var a = [],
inputs = document.querySelectorAll('[name^="a"]');
[].forEach.call(inputs, function(input){
a.push(input.value);
});
console.log(a);
<input name="a1" value="a111"/>
<input name="a2" value="a222"/>
<input name="a3" value="a333"/>
You can do this by adding 'id' attribute similarly 'name' Like,
HTML
<input id="name1" name="name1">
<input id="name2" name="name2">
Javascript
var formData = [];
for(var i=1 ; i<length; i++){
formData.push($('#name'+i).val());
}
Without knowing the form structure you could retrieve it with vanilla javascript as follows:
var arr = [];
var currentElementIndex = 1;
while(document.getElementsByName('a'+currentElementIndex)) {
arr.push(document.getElementsByName('a'+currentElementIndex).value);
currentElementIndex++;
}
Assuming id's are >= 1 and sequential.
Related
how can I use array values as constant like ; aaa 500,bbb 350,ccc 25 and at last calc value 1725.
const vals = ["aaa", "bbb", "ccc"];
clength = vals.length;
i=0;
while (i < clength)
{
vals[i] = document.getElementById(vals[i]).value;
i=i+1
};
document.getElementById("calc").value = (aaa + bbb)*2 + ccc;
<input id="aaa" value="500">
<input id="bbb" value="350">
<input id="ccc" value="25">
<br>
<br>
<br>
<input id="calc">
how can I use array values as constant like ;
aaa 500,bbb 350,ccc 25 and at last calc value 1725.
I want while loop behave like ;
aaa = 500; bbb= 350; ccc = 25;
NOTE : Please think array function as endless.(aaa,bbb,ccc is just samples)
There's many ways to do it but without changing your code much you could use a desctructive assignment:
const [aaa, bbb, ccc] = vals;
document.getElementById("calc").value = (aaa + bbb)*2 + ccc;
It would be better to use a key/value pairs though:
document.getElementById('calc').value = calc(resolveCalcValues());
function calc(vals) {
return (vals.aaa + vals.bbb) * 2 + vals.ccc;
}
function resolveCalcValues() {
return valuesOf('aaa', 'bbb', 'ccc');
}
function valuesOf(...inputIds) {
return inputIds.reduce((vals, id) => {
vals[id] = document.getElementById(id).value;
return vals;
}, {});
}
<input id="aaa" type="number" value="500">
<input id="bbb" type="number" value="350">
<input id="ccc" type="number" value="25">
<input id="calc">
You can dynamically create variables through the window object and remember to convert strings to number to calculate with them:
const vals = ["aaa", "bbb", "ccc"];
for (const val of vals) {
window[val] = +document.getElementById(val).value;
}
document.getElementById("calc").value = (aaa + bbb)*2 + ccc;
<input id="aaa" value="500">
<input id="bbb" value="350">
<input id="ccc" value="25">
<br>
<br>
<br>
<input id="calc">
Following is a more generic approach based on adding different class names to the inputs server side and doesn't involve using any ID or variables at all
function collectionSum (selector){
const els = Array.from(document.querySelectorAll(selector))
return els.reduce((a,c) => a + Number(c.value),0);
}
const combined = collectionSum('.values.combine'),
add = collectionSum('.values.add');
document.getElementById("calc").value = combined * 2 + add;
<input class="values combine" id="aaa" value="500">
<input class="values combine" id="bbb" value="350">
<input class="values add" id="ccc" value="25">
<br>
<br>
<br>
<input id="calc">
I have on page some elements with id`s with number of row in the end. For example
<input type="hidden" name="productid1" id="productid1" value="4941">
<input type="hidden" name="qty1" id="qty1" value="2">
<input type="hidden" name="productid2" id="productid2" value="4942">
<input type="hidden" name="qty2" id="qty2" value="1">
<input type="hidden" name="productid3" id="productid3" value="4941">
<input type="hidden" name="qty3" id="qty3" value="5">
i know elements count, and i`m need make js array with key from productidX value, and value sum of values qtyX
i tryed like that
var out = [];
var tot = jQuery('#totitems').val();
for(var i = 1; i <= tot; i++)
{
out[jQuery('#productid'+i).val()] += parseFloat(jQuery('#devQty'+i).val())
}
but this is not working(
i`m need somesing like taht
[4931] => 7
[4942] => 1
can someone say me right way for this?
sorry for mistakes, english not my native language
Try to use a object {} like this example:
var out = {}; //change to a object
var tot = jQuery('#totitems').val();
for(var i = 1; i <= tot; i++)
{
//now you can acess like properties/hashmap
out[jQuery('#productid'+i).val()] += parseFloat(jQuery('#devQty'+i).val());
}
You also need verify if is undefined before use += like this:
var out = {}; //change to a object
var tot = jQuery('#totitems').val();
for(var i = 1; i <= tot; i++)
{
//now you can acess like properties/hashmap
if(out[jQuery('#productid'+i).val()])
out[jQuery('#productid'+i).val()] += parseFloat(jQuery('#devQty'+i).val());
else
out[jQuery('#productid'+i).val()] = parseFloat(jQuery('#devQty'+i).val());
}
You also have a little mistake using #devQty instead #qty and you need to parse the tot var:
var out = {}; //change to a object
var tot = parseInt(jQuery('#totitems').val());
for(var i = 1; i <= tot; i++)
{
if(out[jQuery('#productid'+i).val()])
out[jQuery('#productid'+i).val()] += parseFloat(jQuery('#qty'+i).val());
else
out[jQuery('#productid'+i).val()] = parseFloat(jQuery('#qty'+i).val());
}
console.log(out);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--For testing-->
<input type="hidden" name="totitems" id="totitems" value="3">
<input type="hidden" name="productid1" id="productid1" value="4941">
<input type="hidden" name="qty1" id="qty1" value="2">
<input type="hidden" name="productid2" id="productid2" value="4942">
<input type="hidden" name="qty2" id="qty2" value="1">
<input type="hidden" name="productid3" id="productid3" value="4941">
<input type="hidden" name="qty3" id="qty3" value="5">
This is another way to do this:
var out = {};
jQuery("[name='product']").each(function(){
var value = parseFloat(jQuery(this).val());
var productID = jQuery(this).data("id");
if(out[productID])
out[productID] += value;
else
out[productID] = value;
});
console.log(out);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name="product" data-id="4941" value="2">
<input type="hidden" name="product" data-id="4942" value="1">
<input type="hidden" name="product" data-id="4941" value="5">
The code below is working fine but what if there are 100 inputs? any shorter way to do this?
function checkTotal() {
var a = document.getElementById("sandwich").value;
var b = document.getElementById("burger").value;
var c = document.getElementById("cake").value;
var d = document.getElementById("coffee").value;
document.getElementById("total").value = parseInt(a) * 10 + parseInt(b) * 5 + parseInt(c) * 15 + parseInt(d) * 20;
}
<form role="form" name="listForm">
<label>Sandwich</label>
<input type="number" id="sandwich" value="0" onkeyup="checkTotal()"><br>
<label>Burger</label>
<input type="number" id="burger" value="0" onkeyup="checkTotal()"><br>
<label>Cake</label>
<input type="number" id="cake" value="0" onkeyup="checkTotal()"><br>
<label>Coffee</label>
<input type="number" id="coffee" value="0" onkeyup="checkTotal()"><br> Total: <input type="text" size="2" name="total" id="total" value="0" />
</form>
1) Here each input article has a different price.
2) The value of the input should be mutiply with its price given(Eg. if the sandwich has a price:30, and user inputs value 2 it should calculte the total=price*input value.)
3) i have my code which is working fine but is the above code is the right way to do?
4) what if there are 100 of article inputs. is there shorter code or should i create variable for each one?
what if there are 100 of article inputs. is there shorter code or
should i create variable for each one?
You can maintain a map
var idPriceMap = {
"sandwich" : 20,
"burger" : 10,
"cake" : 5,
"coffee" : 10
};
You can iterate this and produce your value using reduce
var output = Object.keys( idPriceMap ).reduce( function(a,b){
var value = +document.getElementById( b ).value;
a += value * idPriceMap[ b ];
return a;
}, 0);
document.getElementById( "total" ).value = output;
Another way to try is to give your elements a class and some data attributes that can be retrieved by JavaScript using dataset. You can then use them to make your calculations. That way you get rid of ids and you just have to change the HTML code to add a new element.
function checkTotal() {
var total = 0,
foods = document.querySelectorAll('.food');
for (var i = 0; i < foods.length; i++) {
var food = foods[i],
name = food.dataset.item,
price = parseInt(food.dataset.price),
howMany = parseInt(food.value);
console.log(howMany, name, 'costs', (howMany * price));
total += howMany * price;
}
document.getElementById('total').value = total;
}
<form role="form" name="listForm">
<label>Sandwich</label>
<input class="food" data-item="sandwich" data-price="30" type="number" value="0" onBlur="checkTotal()"><br>
<label>Burger</label>
<input class="food" data-item="burger" data-price="10" type="number" value="0" onBlur="checkTotal()"><br>
<label>Cake</label>
<input class="food" data-item="cake" data-price="5" type="number" value="0" onBlur="checkTotal()"><br>
<label>Coffee</label>
<input class="food" data-item="coffee" data-price="15" type="number" value="0" onBlur="checkTotal()"><br>
Total: <input type="text" size="2" name="total" id="total" value="0" />
</form>
As a side note, you should give a try on Angular or Knockout which can help you to achieve those operations.
I have the below input fields of a processed order form in which:
Order date is given on the name field as array
Cost is given on the value field
<input type="hidden" name="09-15-2017[]" id="dateprice[]" value="1">
<input type="hidden" name="09-13-2017[]" id="dateprice[]" value="3">
<input type="hidden" name="09-13-2017[]" id="dateprice[]" value="4">
<input type="hidden" name="09-15-2017[]" id="dateprice[]" value="5">
The output im trying to get as an alert is:
Total amount on 09-13-2017 is 7
Total amount on 09-15-2017 is 6
This what im currently trying:
var chkprice = 0;
var chkdate = 0;
var inps = document.getElementsByID('dateprice[]');
for (var i = 0; i <inps.length; i++)
{
var inp=inps[i];
var chkprice = inp.value;
if(chkdate==chkdate)
{
chkprice +=chkprice;
}
alert("Total amount on "+chkdate+""+chkprice);
alert(chkprice);
}
I know i have done a terrible javascript scripting.
Can any one guide me in getting values as shown above?
Working fiddle.
First of all the id attribute should be unique in the same document so you could use the common classes instead like :
<input type="hidden" name="09-15-2017[]" class="dateprice" value="1">
<input type="hidden" name="09-13-2017[]" class="dateprice" value="3">
<input type="hidden" name="09-13-2017[]" class="dateprice" value="4">
<input type="hidden" name="09-15-2017[]" class="dateprice" value="5">
Then you could use an object to store the some using the name of inputs as key like :
var inps = document.querySelectorAll('.dateprice');
var totals = {};
//Sum calculation
for (var i = 0; i <inps.length; i++)
{
totals[inps[i].name] = (totals[inps[i].name] || 0) + Number(inps[i].value);
}
//Result display
for (var key in totals) {
if (totals.hasOwnProperty(key)) {
console.log("Total amount on " + key + " is " + totals[key]);
}
}
NOTE : You coudle remove the brackets [ ] from the output using replace() like :
console.log("Total amount on " + key.replace('[]','') + " is " + totals[key]);
Hope this helps.
var inps = document.querySelectorAll('.dateprice');
var totals = {};
//Sum calculation
for (var i = 0; i <inps.length; i++)
{
totals[inps[i].name] = (totals[inps[i].name] || 0) + Number(inps[i].value);
}
//Result display
for (var key in totals) {
if (totals.hasOwnProperty(key)) {
console.log("Total amount on " + key + " is " + totals[key]);
}
}
<input type="hidden" name="09-15-2017[]" class="dateprice" value="1">
<input type="hidden" name="09-13-2017[]" class="dateprice" value="3">
<input type="hidden" name="09-13-2017[]" class="dateprice" value="4">
<input type="hidden" name="09-15-2017[]" class="dateprice" value="5">
I have some line of javascript which is works well if it gets value from the same series of names. But I have a problem later when each values passed to another page which I'd like to break down which value is belongs to. So the question is how can I change the way the script calculate the value from 'name' to 'id'. As the codes below:
<script type="text/javascript">
//auto commas
function doThousands(n) {
n = '' + n;
if (n.length < 4) return n;
var c = n.length % 3;
var pre = n.substring(0, c);
return pre + (pre.length? ',' : '') + n.substring(c).match(/\d{3}/g).join(',');
}
//sub total
function checkTotal() {
document.cc_form.total.value = '';
var sum = <?=$days*$_rate*$_rooms?>;
for (i=0;i<document.cc_form.cost.length;i++) {
if (document.cc_form.cost[i].checked) {
sum = sum + parseInt(document.cc_form.cost[i].value);
}
}document.cc_form.total.value = doThousands(sum);
}
</script>
And this is the HTML:
<form name="cc_form" id="cc_form" method="post" action="/">
<label for="transfer1"><input type="checkbox" id="transfer1" name="cost" value="800" autocomplete="off" onchange="checkTotal()" /> Taxi (800 THB | 2 pax)</label><br />
<label for="transfer2"><input type="checkbox" id="transfer2" name="cost" value="1200" autocomplete="off" onchange="checkTotal()" /> Mini Van (1,200 THB | 6 pax)</label><br />
<label for="xbed"><input type="checkbox" id="xbed" name="cost" value="1200" autocomplete="off" onchange="checkTotal()" /> Extra Bed (1,200 THB)</label><br />
<input type="text" id="total" name="total" />
</form>
document.getElementById http://www.w3schools.com/jsref/met_doc_getelementbyid.asp