不要在onchange事件上提交表格

时间:2014-02-24 17:12:55

标签: javascript forms

            <form class="form1">
              <select onchange="this.form.submit()">
                 <option value="">Select a country...</option>
                 <option value="United States">United States</option>
                 <option value="United Kingdom">United Kingdom</option>
                 <option value="Afghanistan">Afghanistan etc...</option>
              </select>
            <input type="text" />
            <button type="submit" />
            </form>

            <form class="form2">
              <select>
                 <option value="">Select a country...</option>
                 <option value="United States">United States</option>
                 <option value="United Kingdom">United Kingdom</option>
                 <option value="Afghanistan">Afghanistan etc...</option>
              </select>
            <input type="text" />
            <button type="submit" />
            </form>

this.form.submit()在选项更改时提交表单。与此相反的是什么? 不需要在变更时提交表格。只有在单击提交按钮时才需要它。

表格2提交变更。如何摆脱它。

2 个答案:

答案 0 :(得分:1)

您的问题出在按钮标记中。它不能被称为<button />。你基本上有第二种形式作为一个按钮。以下代码应该可以使用onSubmit()作为第二种形式:

<form class="form1">
    <select onchange="this.form.submit()">
             <option value="">Select a country...</option>
             <option value="United States">United States</option>
             <option value="United Kingdom">United Kingdom</option>
             <option value="Afghanistan">Afghanistan etc...</option>
    </select>
    <input type="text" />
    <button type="submit">Click me</button>
 </form>
 <form class="form2" onSubmit="doSomething()">
     <select>
             <option value="">Select a country...</option>
             <option value="United States">United States</option>
             <option value="United Kingdom">United Kingdom</option>
             <option value="Afghanistan">Afghanistan etc...</option>
     </select>
     <input type="text" />
     <button type="submit">Click me</button>
  </form>

答案 1 :(得分:0)

使用此:

<form>
 <!-- Note that the onchange has been removed //-->
 <select name="country" id="country">
    <option value="">Select a country...</option>
     <option value="United States">United States</option>
     <option value="United Kingdom">United Kingdom</option>
     <option value="Afghanistan">Afghanistan etc...</option>
 </select>
 <input type="text" />
 <input type="submit" value="Submit" name="submit" id="submit/>
</form>

您只需删除onchange="this.form.submit()"即可在选择值更改时停止提交表单。