JavaScript DHTML/Event onMethod/onSubmit

Материал из Web эксперт
Перейти к: навигация, поиск

onsubmit action

  

<html>
<head>
  
  <script type="text/javascript">
     function confirmAction() {
       return confirm("Do you really want to do this?")
     }
  </script>
</head>
<body>
<form action="" onsubmit="return confirmAction()" method="post">
    <textarea name="comments" rows="6" cols="46"></textarea>
    <input type="submit" value="Submit" />
</form>
</body>
</html>



"onSubmit" Example

 
    
<html>
<body>
<form name="form1" 
      method="post" 
      action="" 
      onsubmit="alert("The form is being submitted")">
   <input type="text" name="textfield">
   <input type="submit" value="Submit">
</form>
</body>
</html>



Validate form in onsumbit function

 

<html>
<head>
<title>Try/Catch</title>
</head>
<body>
<form name="formexample" id="formexample" action="#">
<div id="valueDiv">Enter a Number Between 1 and 100: <input id="num" name="num"></div>
<div><input id="submit" type="submit"></div>
</form>
<script type="text/javascript">
function checkValid() {
    try {
        var numField = document.forms[0]["num"];
        if (isNaN(numField.value)) {
            throw "Not a number";
        }
        if ((numField.value > 100) || (numField.value < 1)) {
            numField.style.background = "#FF0000";
            return false;
        }
        else {
            numField.style.background = "#FFFFFF";
            return true;
        }
    } catch(errorObject) {
        document.write(errorObject);
        document.write("<BR>");
    } finally {
        document.write("finally.");
    }
}
function init() {
    document.forms[0].onsubmit = function() { return checkValid() };
}
window.onload = init;
</script>
</body>
</html>