form checks script


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <script type="text/javascript">
  2. function checkform(form) {
  3. var texts = new Array('name','email','text');
  4. var textnames = new Array('Name','Email','Textarea');
  5. var radios = new Array('radio');
  6. var radionames = new Array('Radio');
  7. var checkboxes = new Array('check');
  8. var checkboxnames = new Array('Checkbox');
  9. var i, j;
  10. var missing = "";
  11. var checkvalue = new Array();
  12. for (i = 0; i < texts.length; i++) {
  13. if (form.elements[texts[i]].value == "") {
  14. missing += textnames[i] + "\n";
  15. }
  16. }
  17. for (i = 0; i < radios.length; i++) {
  18. var radioelement = form.elements[radios[i]];
  19. for (j = 0; j < radioelement.length; j++) {
  20. if (radioelement[j].checked) {
  21. checkvalue[i] = radioelement[j].value;
  22. break;
  23. }
  24. }
  25. if (!(checkvalue[i])) {
  26. missing += radionames[i] + "\n";
  27. }
  28. }
  29. if (missing != "") {
  30. alert("Please input the following items.:\n" + missing);
  31. return false;
  32. }
  33. return true;
  34. }
  35. </script>
  36. <form method="post" action="" onsubmit="return checkform(this);">
  37. <fieldset>
  38. <legend>Test Form</legend>
  39. <dl>
  40. <dt><label for="name">Name</label></dt>
  41. <dd><input type="text" name="name" id="name" value="" /></dd>
  42. <dt><label for="email">Email</label></dt>
  43. <dd><input type="text" name="email" id="email" value="" /></dd>
  44. <dt>Radio</dt>
  45. <dd>
  46. <ul class="inline">
  47. <li><input type="radio" name="radio" id="Yes" value="Yes" /><label for="Yes">Yes</label></li>
  48. <li><input type="radio" name="radio" id="No" value="No" /><label for="No">No</label></li>
  49. </ul>
  50. </dd>
  51. <dt><label for="text">Textarea</label></dt>
  52. <dd><textarea name="text" id="text" rows="10" cols="50" onfocus="if (this.value=='Leave your messeage here.') this.value='';">Leave your messeage here.</textarea></dd>
  53. </dl>
  54. <div class="submit">
  55. <label for="check"><input type="checkbox" name="check" id="check" value="check" />Checkbox</label>
  56. <input type="submit" value="Submit" />
  57. </div>
  58. </fieldset>
  59. </form>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.