0

I created a form to be processed with javascript only (no submit) and found that Google Chrome was erasing all the inputs when I popped up an alert. After some experimenting, I found that Chrome behaves differently depending on whether the javascript alert is called from button element or an input element. In particular, the HTML button causes the text in the input box to be deleted when you click OK. This does not happen in IE. I have not tried it in other browsers. It does not happen with the input element, and it does not happen with the button element if it is outside the form.

Has anyone else noticed this, or know of a reason why it should be so?

<form>
<p>Enter some text in the input box, then click one of the buttons.</p>
<input type="text"><br>
<input type="button" onclick="alert('What happens to form values?')" value="Input button">    <br>
<button onclick="alert('What happens to form values?')">HTML button</button>
</form>
4

2 回答 2

0

基于 w3schools http://www.w3schools.com/tags/att_button_type.asp

始终指定元素的类型属性。不同的浏览器可能对元素使用不同的默认类型。

在您的情况下,您希望类型为button(否则某些浏览器将默认为submit

<button type="button" onclick="alert('What happens to form values?')">HTML button</button>
于 2013-05-19T21:47:48.780 回答
0

<button>单击时正在提交表单。
提交表单会重新加载页面。

为防止这种情况,请添加return false到处理程序的末尾。

于 2013-05-19T19:21:12.000 回答