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
Related
I have 1 input. And it has to print out 2 outputs 1 with -1 to the output and the other with -2. But the output doesn't show anything. can someone tell me what I'm doing wrong here.
Code:
// Meters en Centimeters value
function updateTotal() {
const list = document.getElementsByClassName("AutosubmitCalculator");
const values = [];
for (let i = 0; i < list.length; ++i) {
values.push(parseFloat(list[i].value));
}
let total = values.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
});
document.getElementById("schermentotaal").value = total - 2;
document.getElementById("schermentotaal2").value = total - 1;
}
HTML Input:
<div class="InputField InputMeters">
<input type="tel" name="iFenceMeters" id="FenceMeters" class="AutosubmitCalculator" data-minimum-length="1" tabindex="1" placeholder="00" maxlength="3" value="">
<div class="FormExclamation Tipped Hidden" id="FormCalculatorExclamationFence">0</div>
</div>
HTML Output:
<div class="SummaryRow">
<strong>Schermen</strong>
<input name="schermentotaal" type="text" id="schermentotaal" value=""></input>
</div>
<div class="SummaryRow">
<strong>Palen en onderplaten</strong>
<input name="schermentotaal2" type="text" id="schermentotaal2" value=""></input>
</div>
Thanks in advance :D
You're not calling your updateTotal anywhere. I suggest you run this function on the oninput event on your input field. This will make it so that whenever you enter a number it will run the function updateTotal.
You also have some additional errors, such as you are trying to get the element with the id total but don't have an element with this id in your HTML.
document.getElementById("total").value
I've changed this to be schermentotaal2 which is a valid id in your HTML:
document.getElementById("schermentotaal2").value
See working example below:
function updateTotal() {
const list = document.getElementsByClassName("AutosubmitCalculator");
const values = [];
for (let i = 0; i < list.length; i++) {
values.push(parseFloat(list[i].value));
}
let total = values.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
});
document.getElementById("schermentotaal").value = (total - 2) || '';
document.getElementById("schermentotaal2").value = (total - 1) || '';
}
<div class="InputField InputMeters">
<input type="tel" name="iFenceMeters" id="FenceMeters" class="AutosubmitCalculator" data-minimum-length="1" tabindex="1" placeholder="00" maxlength="3" value="" oninput="updateTotal()" />
<div class="FormExclamation Tipped Hidden" id="FormCalculatorExclamationFence">0</div>
</div>
<div class="SummaryRow">
<strong>Schermen</strong>
<input name="schermentotaal" type="text" id="schermentotaal" value="" />
</div>
<div class="SummaryRow">
<strong>Palen en onderplaten</strong>
<input name="schermentotaal2" type="text" id="schermentotaal2" value="" />
</div>
Also, if you only have one input you may want to reconsider using a class to get the input value for this as you don't require a loop to get the value from one input field.
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 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.
This question already has answers here:
How can I access object properties containing special characters?
(2 answers)
Closed 9 years ago.
The old html and javascript code:
<tr>
<input id="pret_id_1" type="text" name="pret" />
<input id="val_id_1" type="text" name="val"/>
<input id="val_tva_id_1" type="text" name="val_tva"/>
<input id="cant_id_1" type="text" name="cant" />
</tr>
<script>
var x=document.form_factura;
x.val.value = (x.pret.value * x.cant.value).toFixed(2) ;
x.val_tva.value = ((x.pret.value * x.cant.value) * tva_val).toFixed(2);
if(!/^[a-z()+ A-Z()-]*$/.test(x.val_tva.value)){
var suma = (x.pret.value * x.cant.value)- (-x.val_tva.value);
} else {
var suma = (x.pret.value * x.cant.value);
}
x.suma.value = suma.toFixed(2);
...
</script>
I try to multiply this .. and I added arrays in the name elements .
<tr class="row1">
<input id="pret_id_1" type="text" name="pret[]" />
<input id="val_id_1" type="text" name="val[]"/>
<input id="val_tva_id_1" type="text" name="val_tva[]"/>
<input id="cant_id_1" type="text" name="cant[]" />
</tr>
<tr class="row2">
<input id="pret_id_2" type="text" name="pret[]" />
<input id="val_id_2" type="text" name="val[]"/>
<input id="val_tva_id_2" type="text" name="val_tva[]"/>
<input id="cant_id_1" type="text" name="cant[]" />
</tr>
How can I update the javascript code for array input name elements ??
if it's only one row (.row1) the javascript not working.. must be at least 2 elements with same name.
EDIT: I forgot to mention that I use php and mysql to store the data.
Thanks.
First you should not add the [] in the fields' names:
<tr class="row1">
<input id="pret_id_1" type="text" name="pret" />
<input id="val_id_1" type="text" name="val"/>
<input id="val_tva_id_1" type="text" name="val_tva"/>
<input id="cant_id_1" type="text" name="cant" />
</tr>
<tr class="row2">
<input id="pret_id_2" type="text" name="pret" />
<input id="val_id_2" type="text" name="val"/>
<input id="val_tva_id_2" type="text" name="val_tva"/>
<input id="cant_id_1" type="text" name="cant" />
</tr>
Then x.val will return an array of DOM elements (instead of one single element like before):
<script>
var x=document.form_factura;
for(var i=0; i<x.pret.length; i++) {
x.val[i].value = (x.pret[i].value * x.cant[i].value).toFixed(2) ;
x.val_tva[i].value = ((x.pret[i].value * x.cant[i].value) * tva_val).toFixed(2);
if(!/^[a-z()+ A-Z()-]*$/.test(x.val_tva.value)){
var suma = (x.pret[i].value * x.cant[i].value)- (-x.val_tva[i].value);
} else {
var suma = (x.pret[i].value * x.cant[i].value);
}
x.suma[i].value = suma.toFixed(2);
...
}
</script>
Well you have unique ids so you can loop
for(var i=1;i<=2;i++) {
var pret = document.getElementById("pret_id_" + i );
var cant = document.getElementById("cant_id_" + i );
var val = document.getElementById("val_id_" + i );
val.value = (pret.value * cant.value).toFixed(2) ;
}
if you want to do it by name,
var pretElems = document.form_factura["pret[]"];
var cantElems = document.form_factura["cant[]"];
var valElems = document.form_factura["val[]"]];
for(var i=1;i<=2;i++) {
var pret = pretElems[i];
var cant = cantElems[i];
var val = valElems[i];
val.value = (pret.value * cant.value).toFixed(2) ;
}
I need a basic loop to sum two fields. I just get it to work for one group, but the others remain the same. I know I need some kind of array to solve this, but I can't work it out. (Notice, they are 50 groups in the original project, but I just added 2) Here is the code:
HTML
<label>Value 1:</label><input type="text" name="value1[]" id="txtval1"><br>
<label>Value 2:</label><input type="text" name="value2[]" id="txtval2"><br>
<label>Total:</label><input type="text" name="total[]" id="txttotal"><br><br>
<label>Value 1:</label><input type="text" name="value1[]" id="txtval1"><br>
<label>Value 2:</label><input type="text" name="value2[]" id="txtval2"><br>
<label>Total:</label><input type="text" name="total[]" id="txttotal">
<br><br>
<button type="button" onclick="myFunction(); return false;">Get Total</button>
Javascript
<script type="text/javascript">
function myFunction()
{
var val1 = document.getElementById('txtval1').value;
var val2 = document.getElementById('txtval2').value;
var total = document.getElementById('txttotal');
var sum = parseInt(val1) + parseInt(val2);
if (val1.value!='' && val2.value!=''){
total.value='';
total.value = total.value + sum;
}
}
</script>
I don't know why this doen't work on my fiddle, but does in my local machine. Here is the Fiddle
I think that giving the same ID to two elements It is mistake.
You have to give a different ID for each element and pass them on for.
Look at this fiddle:
http://jsfiddle.net/83m6e/
EDIT: I changed the fiddle for option2:
http://jsfiddle.net/83m6e/3/
You also can put each segment into a div and then do not change the names.
You can not add up to arrays in order to add up their elements. You must do it one by one. Try this code:
<html>
<head>
<script type="text/javascript">
function myFunction()
{
var count = 3;
var val1, val2, sum;
for (var i = 0; i < count; i++)
{
val1 = document.getElementById('txtval1_' + i).value;
val2 = document.getElementById('txtval2_' + i).value;
sum = parseInt(val1) + parseInt(val2);
document.getElementById('txttotal_' + i).value = sum;
}
}
</script>
</head>
<body>
<label>Value 1:</label><input type="text" id="txtval1_0"><br>
<label>Value 2:</label><input type="text" id="txtval2_0"><br>
<label>Total:</label><input type="text" id="txttotal_0"><br><br>
<label>Value 1:</label><input type="text" id="txtval1_1"><br>
<label>Value 2:</label><input type="text" id="txtval2_1"><br>
<label>Total:</label><input type="text" id="txttotal_1"><br><br>
<label>Value 1:</label><input type="text" id="txtval1_2"><br>
<label>Value 2:</label><input type="text" id="txtval2_2"><br>
<label>Total:</label><input type="text" id="txttotal_2"><br><br>
<button type="button" onclick="myFunction(); return false;">Get Total</button>
</body>
</html>