简体   繁体   中英

Onclick shouldn't trigger form data submission

I just found out that every time onclick event for my <button> placed inside <form> tag triggers, form submits it's data as if i clicked <input type='submit'> . I don't want that. Buttons inside my form serve other task, form shouldn't submit data after i clicked one of them.

To be more clear, i want this code:

<form action="http://www.google.com" method="POST">
    <button onclick="alert('hi!')">Button</button>
    <br>
    <input type="submit" value="submit"/>
</form>

to show alert "hi!" when i click on the Button and it shouldn't open Google after that. It should only show Google when i press "submit".

Specify type="button" :

<button type="button" onclick="alert('hi!')">Button</button>

From the linked article:

This [submit] is the default if the attribute is not specified

尝试这个..

onclick="alert('hi!'); return false;"

使用jQuery时,请使用span而不是输入,请使用.button调用,然后设置click事件。

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