I have an Ajax call that loops through a json file with the following code:
It calls a function in the form tag as follows:
When I try to validate the quantity to make sure that it’s a positive number less than ten, I use the following javascript:
function myFunction() {
var x;
x = document.getElementById(‘numb’).value;
alert(x);//this prints 0 every time
if ( isNaN(x) || (x < 0) || (x > 10)) {
alert(“Quantity must be a positive number less than 10.”);
event.preventDefault();
return false;
} else {
alert(“Input OK”);
}
}
The problem is that it doesn’t get the $_POST value of the textbox, it gets the value of zero like how the textbox is initialized every time.
A programming friend of mine pointed out that it’s iterating through a loop of ids and the id is the same for every text input so I changed it to:
and I changed my function to:
function myFunction() {
var x, i, y;
for (i = 1; i < 7; i++) {
y = ‘numb_’ + i;
x = document.getElementById(y).value;
//alert(y);
}
if ( isNaN(x) || (x < 0) || (x > 10)) {
alert("Quantity must be a positive number less than 10.");
event.preventDefault();
return false;
} else {
alert(“Input OK”);
}
}
alert(y); prints out numb_1 every time so it’s not looping properly. How can I improve my loop?
Hello and welcome!
The only problem I see is that You’re using the wrong type of quotes:
function myFunction() {
var x, i, y;
for (i = 1; i < 7; i++) {
// Wrong:
// y = ‘numb_’ + i;
y = 'numb_' + i;
x = document.getElementById(y).value;
//alert(y);
if (isNaN(x) || (x < 0) || (x > 10)) {
alert("Quantity must be a positive number less than 10.");
event.preventDefault();
return false;
} else {
// Wrong
// alert(“Input OK”);
alert("Input OK");
}
}
}
With the help of a participant at another forum, I was able to find a solution. It looks like this:
function myFunction() {
var x, y;
var elements = document.querySelectorAll(’[id^=“numb_”]’);
for (var i = 1; i < elements.length; i++) {
y = elements[i].id;
x = document.getElementById(y).value;
if ( isNaN(x) || (x < 1) || (x > 10)) {
alert("Quantity must be a positive number less than 10.");
event.preventDefault();
return false;
} else {
return true;
}
}
}