当我单击表单中的按钮时,表单已提交.如何避免这种情况?

2022-01-31 00:00:00 ruby-on-rails html twitter-bootstrap

我使用 twitter-boostrap,我想在我的表单中使用 这些单选按钮.问题是当我点击任何这些按钮时,表单会立即提交.如何避免这种情况?我只想使用默认按钮,例如单选按钮.

I use twitter-boostrap and I'd like to use these radio-buttons in my form. The problem is when I click on any of these buttons, the form is immediately submitted. How to avoid this? I just want to use default buttons like radio-buttons.

来自:

<%= form_for @product do |f| %>
    <div class="control-group">
      <%= f.label :type, :class => 'control-label' %>

      <div class="controls">
        <div class="btn-group" data-toggle="buttons-radio">
          <button class="btn">Button_1</button>
          <button class="btn">Button_2</button>
        </div>
      </div>

    </div>

    <div class="form-actions">
      <%= f.submit nil, :class => 'btn btn-primary' %>
      <%= link_to 'Cancel', products_path, :class => 'btn' %>
    </div>
<% end %>

javascript:

javascript:

// application.js
$('.tabs').button();

推荐答案

从细HTML5 规范:

未指定 type 属性的 button 元素与将 type 属性设置为 "submit" 的按钮元素表示相同的东西.

A button element with no type attribute specified represents the same thing as a button element with its type attribute set to "submit".

还有一个 <button type="submit"> 提交表单,而不是像一个简单的 <button type="button"> push-button.

And a <button type="submit"> submits the form rather than behaving like a simple <button type="button"> push-button.

HTML4 规范 说了同样的话:

type = submit|button|reset [CI]
此属性声明按钮的类型.可能的值:

type = submit|button|reset [CI]
This attribute declares the type of the button. Possible values:

  • submit:创建提交按钮.这是默认值.
  • reset:创建一个重置按钮.
  • button:创建一个按钮.
  • submit: Creates a submit button. This is the default value.
  • reset: Creates a reset button.
  • button: Creates a push button.

所以你的 <button> 元素:

<button class="btn">Button_1</button>
<button class="btn">Button_2</button>

与这些相同(在兼容的浏览器中):

are the same as these (in compliant browsers):

<button type="submit" class="btn">Button_1</button>
<button type="submit" class="btn">Button_2</button>

只要您点击其中一个按钮,您就会提交表单.

and any time you hit one of those buttons you'll submit your form.

解决方案是使用普通按钮:

The solution is to use plain buttons:

<button type="button" class="btn">Button_1</button>
<button type="button" class="btn">Button_2</button>

某些版本的 IE 默认为 type="button",尽管标准有什么规定.在使用 <button> 时,您应该始终指定 type 属性,以确保您获得预期的行为.

Some versions of IE default to type="button" despite what the standard says. You should always specify the type attribute when using a <button> just to be sure that you will get the behavior you're expecting.

相关文章