Отправьте HTML форм, которые содержат динамические c идентификаторы - PullRequest
0 голосов
/ 20 февраля 2020

У меня есть 2 HTML формы, которые содержат динамические c ID-атрибуты. Я хочу хранить данные с помощью AJAX звонка из каждой формы HTML отдельно. В настоящее время AJAX вызов работает только для одной HTML формы, когда я использую stati c имя ID «surveyImage».

Я не знаю, как я могу с помощью jQuery вызвать метод submit() индивидуально для каждой формы. Есть ли способ решить эту проблему?

Форма с id = "surveyImage13"

 <form method="POST" action="http://localhost/1/467/survey" accept-charset="UTF-8" id="surveyImage13" role="form" class="form-material m-t-40" novalidate="novalidate"> 
    <div class="row">   
        <div class="col-lg-12">
            <input name="questionnaire_pivot_id" id="questionnaire_pivot_id13" class="questionnaire_pivot_id" type="hidden" value="13">     
            <input name="questionnaire_id" id="questionnaire_id" class="questionnaire_id" type="hidden" value="1">
            <input name="survey_image_id" id="survey_image_id" class="survey_image_id" type="hidden" value="467">

 ...                
            <div class="row" style="margin-bottom: 5%;">
                <div class="col-xl-2 col-lg-3 col-md-3">
                     <button id="add" class="btn  btn-default btn-md-6" type="submit" style="margin-top: 11%;">Save</button>
                </div>           
            </div>       
     </form>

Форма с ID = "surveyImage18"

<form method="POST" action="http://localhost/2/467/survey" accept-charset="UTF-8" id="surveyImage18" role="form" class="form-material m-t-40" novalidate="novalidate"> 
      <div class="row">   
        <div class="col-lg-12">
            <input name="questionnaire_pivot_id" id="questionnaire_pivot_id18" class="questionnaire_pivot_id" type="hidden" value="18">     
            <input name="questionnaire_id" id="questionnaire_id" class="questionnaire_id" type="hidden" value="2">
           <input name="survey_image_id" id="survey_image_id" class="survey_image_id" type="hidden" value="467">

...

            </div>
        </div>

    <div class="row" style="margin-bottom: 5%;">
        <div class="col-xl-2 col-lg-3 col-md-3">
             <button id="add" class="btn  btn-default btn-md-6" type="submit" style="margin-top: 11%;">Save</button>
        </div>           
    </div>       
</form>

AJAX Звоните

<script type="text/javascript">
 $("#surveyImage13").validate({
                    rules: {
                         'responses[]': {
                            required:true                         
                        }
                    },
                     // change name of error class that is assigned to input fields
    errorClass: 'error_validate',

    errorPlacement: function (label, element) {


        // default
        if (element.is(':radio')) {
            label.insertAfter(element.parent('.form-check-inline'));
        }
        else {
            label.insertAfter(element);
        }
    }

     });
</script>


<script type="text/javascript">

     $("#surveyImage13").submit(function(e) {
        e.preventDefault();

        var route=$('#surveyImage13').attr('action');
        var pivot_id = $("#questionnaire_pivot_id").val(); 



        // Get values of checked checkboxes
        var responses = $('.form-check-inline input').filter(':checked').map(function() {
          return this.value;
        }).get();

     var isFormValid = $("#surveyImage13").valid();

    if(isFormValid){

        $.ajax({
          type: "POST",
          url: route, 
          data: {'responses': responses, 'pivot_id': pivot_id},
          success: function(response){


            $("#surveyImageForm").css("display", "none");
            $("#surveyImageAjax").css("display", "block");

            $('#SurveyTableAjaxColumn1').append(response[1]); 
            $('#SurveyTableAjaxColumn2').append(response[0]); 
          },
          error: function(){
            console.log('Error');
          }
        })
        }
     });

</script>

Ответы [ 4 ]

1 голос
/ 20 февраля 2020

Почему бы не дать вашим формам общее class

$('.myClass').validate({ ...
})


$('.myClass').submit(...
0 голосов
/ 20 февраля 2020

Спасибо за все ответы, но я нашел решение. Я работаю в LARAVEL, поэтому я использовал foreach l oop, на основе которого я смог назначить динамический c идентификатор для HTML форм.

@foreach($questionnaire_by_images as $t)
   <form id="surveyImage{{$t->id}}">...</form>
   <form id="surveyImage{{$t->id}}">...</form>
@endforeach

script

 @foreach($questionnaire_by_images as $t)
    <script type="text/javascript">
        $( document ).ready(function() {    

             $("#surveyImage{{$t->id}}").validate({
                                rules: {
                                     'responses[]': {
                                        required:true                         
                                    }
                                },
                                 // change name of error class that is assigned to input fields
                errorClass: 'error_validate',

                errorPlacement: function (label, element) {


                    // default
                    if (element.is(':radio')) {
                        label.insertAfter(element.parent('.form-check-inline'));
                    }
                    else {
                        label.insertAfter(element);
                    }
                }

                 });


                 $("#surveyImage{{$t->id}}").submit(function(e) {
                    e.preventDefault();

                    var route=$('#surveyImage{{$t->id}}').attr('action');

                    var survey_image_pivot = $("#survey_image_pivot{{$t->id}}").val(); 

                    // Get values of checked checkboxes
                    var responses = $('.form-check-inline .radio{{$t->id}}').filter(':checked').map(function() {
                      return this.value;
                    }).get();

                 var isFormValid = $("#surveyImage{{$t->id}}").valid();

                if(isFormValid){

                    $.ajax({
                      type: "POST",
                      url: route, 
                      data: {'responses': responses, 'survey_image_pivot': survey_image_pivot},
                      success: function(response){


                        $("#surveyImageForm{{$t->id}}").css("display", "none");
                        $("#surveyImageAjax{{$t->id}}").css("display", "block");

                        $('#SurveyTableAjaxColumn1{{$t->id}}').append(response[1]); 
                        $('#SurveyTableAjaxColumn2{{$t->id}}').append(response[0]); 
                      },
                      error: function(){
                        console.log('Error');
                      }
                    })
                    }
                 });
        });
        </script>
    </script>

  @endforeach
0 голосов
/ 20 февраля 2020

1. Вместо события отправки используйте событие нажатия кнопки 2. Получите идентификатор формы и сохраните его 3. Используйте эту переменную там, где вам нужен идентификатор

   $(".btn").click(function(e) {
    e.preventDefault();

    var formId = '#'+ $(this).parents('form').attr('id');

    var route=$(formId).attr('action');
    var pivot_id = $("#questionnaire_pivot_id").val(); 



    // Get values of checked checkboxes
    var responses = $('.form-check-inline input').filter(':checked').map(function() {
      return this.value;
    }).get();

    var isFormValid = $(formId).valid();

    if(isFormValid){

    $.ajax({
      type: "POST",
      url: route, 
      data: {'responses': responses, 'pivot_id': pivot_id},
      success: function(response){


        $("#surveyImageForm").css("display", "none");
        $("#surveyImageAjax").css("display", "block");

        $('#SurveyTableAjaxColumn1').append(response[1]); 
        $('#SurveyTableAjaxColumn2').append(response[0]); 
      },
      error: function(){
        console.log('Error');
      }
    })
  }
});
0 голосов
/ 20 февраля 2020

Исходя из предоставленной вами конфигурации, jQuery не сможет выполнить действие отправки. Селектор jQuery имеет значение #surveyImage, что не соответствует никаким атрибутам id в предоставленном HTML.

<form id="surveyImage13">...</form>
<form id="surveyImage18">...</form>
$("#surveyImage").submit...

Думаю, вы сможете решить проблему, используя другую строку селектора запросов.

$('#surveyImage13 #surveyImage18').submit...

или ...

$('form[id^="surveyImage"]').submit...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...