0

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:

<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){
        alert("yes.");
        return false;

    }
    return true;
}
</script>

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?

2 Answers 2

2

I suppose you have this code below, just change onsubmit to onclick

<?php
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 />";
?>
<input type="submit" onclick = 'return validate()' value="Submit booking details">

<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){
        alert("yes.");
        return false;

    }
    return true;
}
</script>
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.