【问题标题】:Clear modal fields after closing modal关闭模态后清除模态字段
【发布时间】:2016-10-21 05:34:17
【问题描述】:

我有这个模态

<form id="contactModal">
<div id="mymodal2" class="" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
     <div class="modal-dialog">
           <div class="modal-content">
              <div class="modal-header">                  
              <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
                <span class="modal-title th2" id="lblModalLabel" name="lblModalLabel">Contact</span>
            </div>
            <div class="modal-body">

我想要的是每次关闭时清除模态,所以我写了一个这样的脚本:

function clear() {
    $("#txtNombreCompleto").val("");
    $("#txtNombreEmpresa").val("");
    $("#exampleInputEmail2").val("");
    $("#dropOficina").val("");
    $("#txtTelefono").val("");
    $("#txtMensaje").val("");
}
$('#mymodal').on('hidden', function(){
    $.clear(this)
});

所以我在模态中的输入是这样的:

 <input type="text" class="form-control" id="txtNombreCompleto" name="txtNombreCompleto" placeholder="Nombre completo">

但是当我关闭模态时,它不会运行该功能,当模态关闭时如何运行该功能?问候

【问题讨论】:

  • 试试这个 $('#myModal').on('hidden.bs.modal', function () { // 做点什么... })
  • 我做了,但不运行,我也把脚本放在控制台上,它可以工作@Sami
  • 检查您的页面是否有 JavaScript 错误。
  • @Sami : 把你的代码放在$(document).ready(function() { /*... here ....*/ });

标签: javascript c# twitter-bootstrap


【解决方案1】:

只需在bootstrap modal hide.bs.modal event(or hidden.bs.modal) 处理程序中调用clear(); 或将函数设置为回调。还将您的代码放在document ready handler 中,以便在加载页面后附加事件处理程序。

$(document).ready(function() {
  $('#mymodal').on('hidden', function() {
    clear()
  });
});

或获取模态内的所有元素并设置值

$(document).ready(function() {
  $('#mymodal').on('hidden', function() {
    $(':input', this).val('');
  });
});    

【讨论】:

  • 谢谢,我的功能不起作用,因为我没有$(document).ready(function() 来启动它。谢谢!
  • @John 很高兴它有帮助:)
  • 我的代码有问题,你能帮帮我吗?
  • @John:有什么问题?
  • 我在我的问题上上传了我的代码,问题是第一个函数('mymodal') 运行得很好,但我的第二个模式不起作用('mymodal2'),如果我用控制台运行它也不要' t 也可以,它运行 js 但不工作......那里可能有什么问题?,
【解决方案2】:

我在我的项目中尝试了此代码,但没有成功。所以我尝试了这个新代码

$(document).ready(function() {
    $('.modal').on('hidden.bs.modal', function(){
        $(this).find('form')[0].reset();
     });
});

【讨论】:

    【解决方案3】:
     $('.btnLogMesaj').click(function () { // your button is clicked
          $('div#demo').empty();  // clear the "div" of the id "demo" 
         *
         * 
         *
      });
    
         <div class="modal-body">
                    <div id="demo">
                        <h4>... Merve's contents </h4>
                    </div>
          </div>
    

    【讨论】:

    • 请添加一些解释。
    猜你喜欢
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多