The illustration below shows this relationship: Note that the 'I' in selected Index needs to be capitalised - Java Script functions and variables are always case-sensitive. Read more about the humble checkbox in our HTML5 Checkbox Validation article.
Tried setting it up on onsubmit on both form and button and no go.
This is done using HTML5 form validation techniques and CSS, but it only validates the input format (pattern) and not the actual values.
Through Java Script, we can validate name, password, email, date, mobile number etc fields.
In this example, we are going to validate the name and password.
The problem is that, to have the data submitted in a 'nice' format to the server, the function returns an array containing all the selected checkbox values. In more complicated forms you will want to set conditions on the form that combine multiple elements.
Normally you would modify this so that you could submit or not submit the form based on the number of items selected. For example, a text input that only needs to have a value if a checkbox is checked: Using simple logical operators and the functions supplied above you can do all sorts of client-side form validation.
Only when all conditions have been satisfied do we reach the command, in which case the form will be submitted.
You'll see that the all validation scripts presented on this and subsequent pages adhere to the same basic format.
When form input is important, it should always be verified using a secure server-side script.
Otherwise a browser with Java Script disabled, or a hacker trying to compromise your site, can easily submit invalid data. The first test in the example is therefore only necessary in order to provide a different error message when the input is blank.
Most modern browsers now support HTML5 Form Validation making it possible to validate form elements without (or before) any Java Script is triggered.