【问题标题】:How to select a button inside a form tag with javascript?如何使用javascript选择表单标签内的按钮?
【发布时间】:2014-09-25 15:03:08
【问题描述】:

我试图在使用 bootbox 插件提交表单时弹出确认消息。问题是我不知道如何选择表单标签内的按钮。在下面的示例中,确认消息确实适用于表单标签之外的按钮,但不适用于里面的按钮。如何选择包裹在表单标签内的这个按钮?

<div class="bs-example">
<div class="col-md-4 col-md-offset-4">
<form action="#" method="POST">
    <div class="form-group">
        <input type="username" class="form-control" id="inputEmail" placeholder="Username">
    </div>
    <div class="form-group">
        <input type="email" class="form-control" id="inputEmail" placeholder="Email">
    </div>
    <div class="form-group">
        <input type="password" class="form-control" id="inputPassword" placeholder="Password">
    </div>
    <div class="form-group">
        <input type="password" class="form-control" id="inputPassword" placeholder="Repeat password">
    </div>  
    <div class="checkbox">
        <label><input type="checkbox"> Remember me</label>
    </div>
            <button class='btn btn-signup btn-signup-sm' type="submit">Sign up</button>
</form>
</div>
</div>

<button class='btn btn-signup btn-signup-sm' type="submit">Sign up</button>

<script type="text/javascript">
$(document).ready(function(){
$('.btn').on('click', function(){
    bootbox.alert("hello there");
});
});
</script

【问题讨论】:

  • 问题不在于,两个按钮都没有 onclick 处理程序,而是提交了表单,然后重新加载了页面。

标签: javascript bootbox


【解决方案1】:

将javascript代码更改为:

<script type="text/javascript">
$(document).ready(function(){
$('.btn').on('click', function(e){
    e.preventDefault();          // this line is key to preventing page reload
                                 // when user clicks submit button inside form
    bootbox.alert("hello there");
});
});
</script>

【讨论】:

    【解决方案2】:

    为什么不捕捉表单的提交事件?

    给你的表单一个像"&lt;form method="POST" id="my_form"&gt;...&lt;/form&gt;"这样的ID

    并使用:

    $('#my_form').submit(function(){
       bootbox.alert("hello there");
    });
    

    看看你的fiddle here!

    【讨论】:

      猜你喜欢
      • 2019-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      • 1970-01-01
      • 2018-10-05
      相关资源
      最近更新 更多