Madrigone Madrigone - 4 months ago 5x
PHP Question

Validate three number input fields with javascript

I'm currently setting up a page with PHP which has three numeric input fields on it. It looks as follows:

echo "Adult Tickets: <input type=\"number\" name=\"adulttickets[]\" value='0' id='adult' min='0' max='10'><br />";
echo "Child Tickets: <input type=\"number\" name=\"childtickets[]\" value='0' id='child' min='0' max='10'><br />";
echo "Student Tickets: <input type=\"number\" name=\"studenttickets[]\" id='student' value='0' min='0' max='10'><br />";

echo <<<_END

<input type="submit" onsubmit = 'return validate()' value="Submit booking details">

I want to use javascript to ensure that the form cannot be submitted if none of the three input types have been altered from their default value of zero. In reflection of this I set up the following JS script:

function validate(){
var adult = document.getElementById('adult').value;
var child = document.getElementById('child').value;
var student = document.getElementById('student').value;

if(adult==0 && child ==0 && student==0){
return false;

return true;

Nothing happens when I run this however. Am I going about this the right way? Is there some better way to achieve the outcome I just described?


you need parse the input values into numbers (currently they are strings even though the input type is number - the value will be a string) before comparing them;

var adult = parseInt(document.getElementById('adult').value);
var child = parseInt(document.getElementById('child').value);
var student = parseInt(document.getElementById('student').value);