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) ;
}
Related
I have wrote a code to split the input into two variables i.e. year and month. But, I am unable to make it work. It does not return the total number of months into the respective text field. Please help me debug my code.
$(function() {
$("#duration").keyup(function() {
var input = document.getElementById('duration').value;
var fields = input.split('.');
var years = fields[0];
var months = fields[1];
var result = years.val() * 12 + months.val();
document.getElementById("totalNumMonths").innerHTML = result;
});
});
<html>
<body>
<table>
<tr>
<td>Calculate Months</td>
<td>
<label>Input Years in the format (year.month e.g. 11.6)</label>
<input class="form-control" name="duration" id="duration" value="" type="number" />
<br/>
<label>Total Months</label>
<input class="form-control" name="totalNumMonths" id="totalNumMonths" value="" type="number" />
</td>
</tr>
</table>
</body>
</html>
Issues with code that I identified and fixed.
You dont need to access years.val() and months.val() because years and months holds string value.
If your input doesnot have a dot, the value for months will be undefined, so you can define years and months as fields[0] || "0" and fields[1] || "0" respectiveley.
Since element with id totalNumMonths is an input. You should set the value and not innerHTML
Since the years and months value produces a string, I have added a + symbol infront of them while setting the value for #totalNumMonths to convert them to number, since we are performing numiric action. Else + symbol on string will perform string concatenation.
Working Fiddle
$(function () {
$("#duration").keyup(function () {
var input = document.getElementById('duration').value;
var fields = input.split('.');
var years = fields[0] || "0";
var months = fields[1] || "0";
var result = +years * 12 + +months;
document.getElementById("totalNumMonths").value = result;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<table>
<tr>
<td>Calculate Months</td>
<td>
<label>Input Years in the format (year.month e.g. 11.6)</label>
<input class="form-control" name="duration" id="duration" value="" type="number" />
<br />
<label>Total Months</label>
<input class="form-control" name="totalNumMonths" id="totalNumMonths" value="" type="number" />
</td>
</tr>
</table>
You were calling val on string elements, which caused errors. And the result was adding months as a string value.
$(function () {
$("#duration").keyup(function () {
var input = document.getElementById('duration').value;
var fields = input.split('.');
var years = parseInt(fields[0]);
var months = parseInt(fields[1]);
var result = (years * 12) + months;
document.getElementById("totalNumMonths").value = result;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<table>
<tr>
<td>Calculate Months</td>
<td>
<label>Input Years in the format (year.month e.g. 11.6)</label>
<input class="form-control" name="duration" id="duration" value="" type="number"/>
<br/>
<label>Total Months</label>
<input class="form-control" name="totalNumMonths" id="totalNumMonths" value="" type="number"/>
</td>
</tr>
</table>
</body>
</html>
In the code snippet, you are having the value of years & months in the respective variables, so you don't need to use years.val() to get that value.
Check this out!!
$(function() {
$("#duration").keyup(function() {
var input = document.getElementById('duration').value;
var fields = input.split('.');
var years = fields[0];
var months = fields[1] || 0;
var result = years * 12 + months;
document.getElementById("totalNumMonths").innerHTML = result;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>Calculate Months</td>
<td>
<label>Input Years in the format (year.month e.g. 11.6)</label>
<input class="form-control" name="duration" id="duration" value="" type="number" />
<br/>
<label>Total Months :</label>
<!-- <input class="form-control" name="totalNumMonths" id="totalNumMonths" value="" type="number" /> -->
<span id="totalNumMonths">0</span>
</td>
</tr>
</table>
Background: I'm practicing arrays and functions and am having trouble computing the sum of array items. I'm pretty sure there is something wrong with the function I'm writing but I'm not sure what. Using 8 input fields I'm pulling data into a array one item at a time and converted to floating numbers(for now...I'll try to fix that later). I've created a function that will compute the total of this list but it only outputs NaN.
Any suggestions are highly appreciated!
function myfunction() {
list = [];
list[0] = parseFloat(document.getElementById('number1').value);
list[1] = parseFloat(document.getElementById('number2').value);
list[2] = parseFloat(document.getElementById('number3').value);
list[3] = parseFloat(document.getElementById('number4').value);
list[4] = parseFloat(document.getElementById('number5').value);
list[5] = parseFloat(document.getElementById('number6').value);
list[6] = parseFloat(document.getElementById('number7').value);
list[7] = parseFloat(document.getElementById('number8').value);
function total(myvals) {
let total = 0;
for (let i = 0; i <= myvals.length; i++) {
total += myvals[i];
}
return total;
}
document.getElementById('results').innerHTML = total(list);
}
<form>
<input type="text" name="number1" id="number1"><br>
<input type="text" name="number2" id="number2"><br>
<input type="text" name="number3" id="number3"><br>
<input type="text" name="number4" id="number4"><br>
<input type="text" name="number5" id="number5"><br>
<input type="text" name="number6" id="number6"><br>
<input type="text" name="number7" id="number7"><br>
<input type="text" name="number8" id="number8"><br>
<input type="submit" value="Compute Score" onclick="javascript:myfunction()">
</form>
<div id="results"></div>
Here is a simple example using a for loop with querySelectorAll.
Additionally, I cleaned up your code a bit. Run the snippet below:
EDIT: Included some comments to show what's happening.
function myfunction() {
let total = 0;
//get the value for each element being called by querySelectorAll
//add values to total to get a sum
document.querySelectorAll('input').forEach(el => total += +el.value);
//append the new value to the results div
document.querySelector('#results').innerHTML = total;
}
<form>
<input type="text" name="number1" id="number1"><br>
<input type="text" name="number2" id="number2"><br>
<input type="text" name="number3" id="number3"><br>
<input type="text" name="number4" id="number4"><br>
<input type="text" name="number5" id="number5"><br>
<input type="text" name="number6" id="number6"><br>
<input type="text" name="number7" id="number7"><br>
<input type="text" name="number8" id="number8"><br>
</form>
<br/><br/>
<button type="submit" onclick="myfunction()">Compute Score</button>
<br/><br/>
<div id="results"></div>
This is resolved. I was able to fix my source code by removing
"<=" in the for loop and adding "<" in its place. Thanks everyone, I will look over everything else for extra practice!
1 - in HTML forms and their elements use names.
2 - each element of a form can be accessed by name with the form as parent
3 - if several elements have the same name (with the same type of preference) then they form an object collection
PS: I have used here [... myForm.numX] to transform the myForm.numX collection to array, so that it can accept the arry.map () method
this way:
const myForm = document.forms['my-form']
, res = document.getElementById('results')
;
myForm.onsubmit = evt =>
{
evt.preventDefault() // disable submit
let list = [...myForm.numX].map(inp => parseFloat(inp.value))
res.textContent = list.reduce((t,v)=>t+v,0)
// control...
console.clear()
console.log( myForm.numX.length, JSON.stringify(list) )
}
<form name="my-form">
<input type="text" name="numX" placeholder="num 1"><br>
<input type="text" name="numX" placeholder="num 2"><br>
<input type="text" name="numX" placeholder="num 3"><br>
<input type="text" name="numX" placeholder="num 4"><br>
<input type="text" name="numX" placeholder="num 5"><br>
<input type="text" name="numX" placeholder="num 6"><br>
<input type="text" name="numX" placeholder="num 7"><br>
<input type="text" name="numX" placeholder="num 8"><br>
<button type="submit">Compute Score</button>
</form>
<div id="results">..</div>
First of all, sorry for the post's title.
I am trying to get references from these questions:
GetElementsByName with array like name
getElementsByName: control by last partial name
How can I select an element by ID with jQuery using regex?
And more or less I understood how to proceed.
I am using this code to check all the <input> and prevent the form from being submitted if any of the field is empty:
$('form[id="insertForm"]').on("submit", function (e) {
var form = document.getElementById("insertPanel");
var inp = form.getElementsByTagName('input');
for(var i in inp){
if(inp[i].type == "text"){
if(inp[i].value == ""){
inp[i].focus();
e.preventDefault();
$("#formAlert").show(400);
break;
}
}
}
});
The "problem", is that I was asked to add an exception, and one of these <input> can be empty.
The form is similar to this, what I post here is simplified:
<form id="insertForm" >
<div id="insertPanel">
<input type="text" name="FOO1" id="FOO1" />
<input type="text" name="FOO2" id="FOO2" />
<input type="text" name="FOO3" id="FOO3" />
<input type="text" name="FOO4" id="FOO4" />
<button type="submit" name="submit" value="Submit" >Send</button>
<table id="tab_logic">
<thead>
<tr>
<th>Bar1</th>
<th>Bar2</th>
<th>Bar3</th>
<th>Bar4</th>
<th>Bar5</th>
<th>Bar6</th>
<th>Bar7</th>
<th>Bar8</th>
<th>Bar9</th>
</tr>
</thead>
<tbody>
<tr id='addr_100'>
<td>
<input type="text" name='prefs[0][FooBar_A]' />
</td>
<td>
<input type="text" name='prefs[0][FooBar_B]' />
</td>
<td>
<input type="text" name='prefs[0][FooBar_C]' />
</td>
<td>
<input type="text" name='prefs[0][FooBar_D]' />
</td>
<td>
<input type="text" name='prefs[0][FooBar_E]' />
</td>
<td>
<input type="text" name='prefs[0][FooBar_F]' />
</td>
<td>
<input type="text" name='prefs[0][FooBar_G]' />
</td>
<td>
<input type="text" name='prefs[0][FooBar_H]'/>
</td>
<td>
<input type="text" name='prefs[0][FooBar_I]' />
</td>
</tr>
<tr id='addr_101'/>
</tbody>
</table>
<a id="add_row">Add Row</a>
<a id='delete_row'>Delete Row</a>
</form>
I removed all the CSS. Kept is really simple.
I was asked to NOT check the input <input type="text" name='prefs[0][FooBar_G]' />
As you can see, it is an array, at every "add row" click, there is a jquery that adds a new row with name='prefs[1][FooBar_A]' and so on.
I tried to work on the for():
$('form[id="insertForm"]').on("submit", function (e) {
var form = document.getElementById("insertPanel");
var inp = form.getElementsByTagName('input');
var SKIP = form.querySelectorAll('input[name$="FooBar_G]"]');
for(var i in inp){
if(inp[i].type == "text"){
if(inp[i].value == ""){
if (SKIP){ console.log("Element " + SKIP.innerText + " found. "); continue; }
inp[i].focus();
e.preventDefault();
$("#formAlert").show(400);
break;
}
}
}
});
And many other versions.. failing.
Anyone knows how to make this working?
let inputs = [...document.querySelectorAll('input')]
let reg = new RegExp('FOO[0-9]', 'g')
let filtered = inputs.filter(({ name }) => name.match(reg))
console.log(filtered)
<input type="text" name="FOO1" id="FOO1" />
<input type="text" name="FOO2" id="FOO2" />
<input type="text" name="FOO3" id="FOO3" />
<input type="text" name="FOO4" id="FOO4" />
<input type="text" name='prefs[0][FooBar_A]' />
<input type="text" name='prefs[0][FooBar_B]' />
<input type="text" name='prefs[0][FooBar_C]' />
<input type="text" name='prefs[0][FooBar_D]' />
$('form[id="insertForm"]').on("submit", function (e) {
var form = document.getElementById("insertPanel")
var reg = new RegExp('FOO[0-9]', 'g')
var inputs = [...document.querySelectorAll('input')].filter(({name}) => name.match(reg))
inputs.forEach((inp, i) => {
if(inp[i].type === "text" && inp[i].value === ""){
inp[i].focus();
$("#formAlert").show(400);
}
})
});
Use querySelectorAll to exclude that input (and to shorten your code). Specifically, the :not([name$=FooBar_G\\]]) selector to exclude the one you want to keep out. It can also be used to specify the text inputs.
You can simply the selector using the *= contains selector if you know that there will not be false positives. :not([name*=FooBar_G])
$('form#insertForm').on("submit", function(event) {
var inputs = this.querySelectorAll("#insertPanel input[type=text]:not([name$=FooBar_G\\]])");
for (var i = 0; i < inputs.length; i++) {
if (!inputs[i].value) {
inputs[i].focus();
event.preventDefault()
$("#formAlert").show(400);
break;
}
}
});
And to do it in a more modern way, I'd do this:
document.querySelector('form#insertForm').addEventListener("submit", function(event) {
const inp = Array.from(
this.querySelectorAll("#insertPanel input[type=text]:not([name$=FooBar_G\\]])")
).find(inp => !inp.value);
if (inp) {
inp.focus();
event.preventDefault()
$("#formAlert").show(400);
}
});
Some things:
1) if(SKIP) will always enter the branch as objects are truthy. You need compare sth (===)
2) If you already include such a heavy library like jquery you should use it everywhere to make it worth it
$('form[id="insertForm"]').on("submit", function (e) {
const inputs = $("#insertPanel > input").toArray();
const skip = $('input[name$="FooBar_G]"]')[0];
for(const input of inputs){
if(input === skip) continue;
if(!input.value){
input.focus();
e.preventDefault();
$("#formAlert").show(400);
break;
}
}
});
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.
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