简体   繁体   中英

Want HTML form submit to do nothing

I want an HTML form to do nothing after it has been submitted.

action=""

is no good because it causes the page to reload.

Basically, I want an Ajax function to be called whenever a button is pressed or someone hits Enter after typing the data. Yes, I could drop the form tag and add just call the function from the button's onclick event, but I also want the "hitting enter" functionality without getting all hackish.

By using return false; in the JavaScript code that you call from the submit button, you can stop the form from submitting.

Basically, you need the following HTML:

<form onsubmit="myFunction(); return false;">
    <input type="submit" value="Submit">
</form>

Then the supporting JavaScript code:

<script language="javascript"><!--
    function myFunction() {
        // Do stuff
    }
//--></script>

If you desire, you can also have certain conditions allow the script to submit the form:

<form onSubmit="return myFunction();">
    <input type="submit" value="Submit">
</form>

Paired with:

<script language="JavaScript"><!--
    function myFunction() {
        // Do stuff
        if (condition)
            return true;

        return false;
    }
//--></script>
<form id="my_form" onsubmit="return false;">

足够的 ...

它也有效:

<form id='my_form' action="javascript:myFunction(); return false;">

How about

<form id="my_form" onsubmit="the_ajax_call_function(); return false;">
 ......
</form>

You can use the following HTML

<form onSubmit="myFunction(); return false;">
  <input type="submit" value="Submit">
</form>
<form onsubmit="return false;">

Use jQuery . Maybe put a div around your elements from the form. Then use preventDefault() and then make your Ajax calls.

As part of the button's onclick event, return false, which will stop the form from submitting.

Ie:

function doFormStuff() {
    // Ajax function body here
    return false;
}

And just call that function on submit button click. There are many different ways.

Use:

<form action='javascript:functionWithAjax("search");'>
  <input class="keyword" id="keyword" name="keyword" placeholder="input your keywords" type="search">
  <i class="iconfont icon-icon" onclick="functionWithAjax("search");"></i>
</form>

<script type="text/javascript">
  function functionWithAjax(type) {
    // Ajax action

    return false;
  }
</script>

In cases where 'return false' doesn't do a thing,

try just passing the event to the form 's onsubmit (not action!)

and simply add event.preventDefault() in that function.

Leave the 'action' from the html. Additional info: action="javascript:etc(event)" didn't work in my tests.

Just replace 'action=""' withonsubmit='return false'. That's it.

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