Python-Ref > Mimo python > JavaScript > Working with forms

Klíčová slova
Knihovní funkce

Working with forms

Javascript can be used to validate forms on the client side. Using the onsubmit handler, one can validate a form before it is submitted and only allow submission if all test are passed (the handler function returns true).
function check_input() {
    var name = document.forms[0].name;
    var booksel = document.forms[0].book;
    var book = booksel.selectedIndex;
    if (name.value == "") {
	alert("You must fill in the name!");
	return false;  // the form will not be submitted
    else if (book == 0) {
	alert("You must select a book!");
	return false;  // the form will not be submitted
    return true; // the form will be submitted

Zdroj: (js4-1.html)
  1   <html xmlns="">
  2   <head>
  3    <title>Javascript example</title>
  4    <meta content="text/html; charset=utf-8" http-equiv="content-Type"/>
  5    <script src="infiles/js4-1.js" type="text/javascript"> </script>
  6   </head>
  7   <body>
  8     <form action="" onsubmit="return check_input()">
  9       <p>Your name: <input type="text" name="name"/></p>
 10       <p>Select a book:
 11       <select name="book">
 12         <option selected="selected" value="default">Choose a book...</option>
 13         <option value="The Hitchhiker's Guide to the Galaxy">The Hitchhiker's Guide to the Galaxy</option>
 14         <option value="So Long, and Thanks for All the Fish">So Long, and Thanks for All the Fish</option>
 15         <option value="Dirk Gently's Holistic Detective Agency">Dirk Gently's Holistic Detective Agency</option>
 16       </select>
 17       </p>
 18       <p><input type="submit"/></p>
 19     </form>
 20   </body>
 21   </html>
Doba běhu: 19.8 ms