Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

javascript - 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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...