简体   繁体   中英

i want to check form validation by input type button, not by submit, could any one help in this?

i want to only validate the form and don't want to submit it, so that i can use the form values in modifying other part of the same html page by calling a function "myfunction()" after form validation. for this i want to use a button suggest me required code.my code is following :-

            <form name="form1">
                <input type="text" name="name1" required></input>
                <button onclick="myfunction()" ></button>        // i want to validation of form by this button
            </form>

You can try this by setting onsubmit event of form to return false; as follows:

<form name="form1" onsubmit="return false;">
    <input type="text" name="name1" required></input>
    <button onclick="myfunction();" ></button>
</form>

This will not submit the form on clicking the button but will execute myfunction() instead.

If you know jQuery, then you can do this as follows:

$('form[name="form1"]').submit(function (event) {
    // This will prevent form being submitted. 
    event.preventDefault();
    // Call your function.
    myfunction();      
});

For maintainability consider adding an event listener to the button by selection instead of inline. When the button is clicked an event object is passed to the callback. Event objects have a number of properties and methods. In this case you're looking for the method "preventDefault" which prevents the default action of the event which in this case is a form submit. An example:

<form name="form1">
  <input type="text" name="name1" required />
  <button id="my-button"></button>
</form>

document.getElementById('my-button').addEventListener('click', function(e){

  e.preventDefault();

  var form = document.forms['form1']; //or this.parentNode

  //do stuff


}, false);

i have achived this goal by modifying code as follow:-

          <form name="form1" onsubmit="myfunction();return false;">
          <input type="text" name="name1" required></input>
          <button >check form and call function</button>  
          </form>

by this i am able to check form and call my function and form is also not submitted in this case. now i want to reset the form without clicking any button. suggest javascript code for this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM