2016-11-21 4 views
2

Я хочу отправить форму в bootstrap modal с помощью кнопки отправки и вернуть ответ на модальный, а затем, если пользователь нажмет обновление, он должен вернуть модальное состояние в предыдущее состояние, теперь работает, но проблема заключается в том, что кнопка SEND не пожары снова после возвращения в прежнее состояние ...JQuery onclick event firing once

Вот код

<!-- the code that represents the modal dialog --> 


    <button data-toggle="modal" data-target="#one_time_sms">LAUNCH SMS MODAL</button> 

<div class="modal fade" id="one_time_sms" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" align="left"> 
<br><br> 
    <div class="modal-dialog" role="document"> 
     <div class="modal-content"> 
      <div class="modal-header"> 
       <button type="button" class="close" data-dismiss="modal">&times;</button> 
       <h4 class="modal-title">Send SMS</h4> 
      </div> 
       <div class="modal-body"> 
       <b>Available Unit for SMS</b> (converted from your credit) - <span style="background:green; color:white; border-radius:3px; padding:3px;">85.2</span><br><br> 

        <form id="contact_form" action="http://localhost/..." method="POST"> 



         <label>Type phone no(s) below </label><br> 
         <textarea style="width: 100%; height: 100px;" name="phone_nos" placeholder="your phone nos here, separate with commas if more than one" required></textarea> 
         <br><br> 

         <label>Type your message below</label><br> 
         <textarea style="width: 100%; height: 120px;" name="message" placeholder="your message here" required></textarea> 

         <br><br> 

         <input type="hidden" name="group_id" value=""> 

         <div class="row"> 

          <div class="col-sm-3"><label>Sender's Identity</label></div> 
          <div class="col-sm-9"> 

          <input name="sender_id" type="text" maxlength="11" placeholder="your Sender id here" value="" required> 

          </div> 

         </div> 

        </form> 
       </div> 
       <div class="modal-footer"> 
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
        <button type="button" id="submitForm" class="btn btn-default">Send</button> 
        <button type="button" id="refreshForm" class="btn btn-default">Refresh Form</button> 
       </div> 
      </div> 
     </div> 
    </div> 




<script> 

var initial_dialog_html = document.getElementById('one_time_sms').innerHTML; 


    $(document).ready(function() { 
     $("#contact_form").on("submit", function(e) { 
      $("#submitForm").remove(); 
      $('#one_time_sms .modal-header .modal-title').html("Message Sending Processing"); 
      $('#one_time_sms .modal-body').html('<br><center>Please wait, we are processing your request....</center></br>'); 
      var postData = $(this).serializeArray(); 
      var formURL = $(this).attr("action"); 
      $.ajax({ 
       url: formURL, 
       type: "POST", 
       data: postData, 
       success: function(data, textStatus, jqXHR) { 
        $('#one_time_sms .modal-header .modal-title').html("Message Status"); 
        $('#one_time_sms .modal-body').html(data); 

       }, 
       error: function(jqXHR, status, error) { 
        console.log(status + ": " + error); 
       } 
      }); 
      e.preventDefault(); 
     }); 

     $("#submitForm").on('click', function() { 
      $("#contact_form").submit(); 
     }); 


     $("#refreshForm").on('click', function() { 
      console.log(initial_dialog_html); 
      $('#one_time_sms').html(initial_dialog_html); 
      //location.reload(); 
     }); 


    }); 

</script>       
+0

сделано: выяснить, как сделать это – user3909617

ответ

0

Я думаю, это происходит потому, что ваш HTML становится пересмотрен после отправки формы. В success обработчике ajax Поста у вас есть следующие строки:

$('#one_time_sms .modal-body').html(data); 

, который удаляет все ранее созданный DOM-элемент и создавая новые. Так что event прослушиватель, ограниченный ранее, не будет работать. Следовательно, ваш код в пределах $("#submitForm").on('click', function() { и $("#refreshForm").on('click', function() { не будет работать в следующий раз. Поэтому, чтобы избежать этого; Вы должны пойти с eventdelegation техника, как показано ниже:

$(document).on('click',"#submitForm", function() { 
     $("#contact_form").submit(); 
    }); 

    $(document).on('click',"#refreshForm", function() { 
     console.log(initial_dialog_html); 
     $('#one_time_sms').html(initial_dialog_html); 
     //location.reload(); 
    }); 

Изменение submit обработчика, а также, как показано ниже:

$(document).on("submit","#contact_form", function(e) { 
    e.preventDefault(); //avoid submitting the form the usual way 
    //your existing code 
    $("#submitForm").remove(); 
+0

Его работу, но на второй клик, он принимает пользователю URL-адрес в атрибуте действия, как я могу сделать возврат ответа на модально вместо того, пользователь к URL-адресу в атрибуте действия формы? – user3909617

+0

@ user3909617 - не могли бы вы попробовать выше модифицированного кода. – vijayP

+0

Он отклоняет модальную кнопку при первом нажатии кнопки SEND – user3909617

0

Если вы хотите, чтобы остаться на той же странице и «избегать» любой перегрузки или отклоняя существующих модальных, чем удалить вашу «отправку» реализации на первом месте.

Я предлагаю использовать привязку событий «кнопки» вместо запуска событий «отправить» и использовать URL-адрес «действия», поскольку вы все равно используете связь ajax.

Итак, что дальше?

  1. Убрать последующие, так как я не нахожу, что это приносит вам какие-либо выгоды.

    $("#submitForm").on('click', function() { 
        $("#contact_form").submit(); 
    }); 
    
  2. Добавить это, это не освобождает существующую открытую модальность, потому что это не формы покориться и вы не использовали данные Отклонить = «модальными» так хорошо, чтобы остаться на тот же модальном.

    $("#submitForm").on("click", function(e) { 
         $("#submitForm").remove(); 
         $('#one_time_sms .modal-header .modal-title').html("Message Sending Processing"); 
         $('#one_time_sms .modal-body').html('<br><center>Please wait, we are processing your request....</center></br>'); 
         var postData = $(this).serializeArray(); 
    
         $.ajax({ 
         url: 'your_url', 
         type: "POST", 
         data: postData, 
         success: function(data, textStatus, jqXHR) { 
          $('#one_time_sms .modal-header .modal-title').html("Message Status"); 
          $('#one_time_sms .modal-body').html(data); 
    
         }, 
         error: function(jqXHR, status, error) { 
          console.log(status + ": " + error); 
         } 
        }); 
        e.preventDefault(); 
    });