Nenad
Nenad

Reputation: 15

Submit HTML forms that contain dynamic IDs

I have 2 HTML forms that contain dynamic ID attributes. What I want is to store data with AJAX call from each HTML form separately. Currently AJAX call works only for one HTML form when I use static ID name "surveyImage".

I don't know how I can with jQuery to call method submit() individually for each form. Is there any way to resolve this issue?

Form with 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>

Form with 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 call

<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>

Upvotes: 0

Views: 698

Answers (4)

Nenad
Nenad

Reputation: 15

Thanks for all answers but I found solution. Im working in LARAVEL therefore I used foreach loop based on which i was able to assign dynamic ID on HTML forms.

@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

Upvotes: 0

harsh_apache
harsh_apache

Reputation: 443

1.Instead of submit event use button click event 2.Get form id and store it 3.use this variable where you need id

   $(".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');
      }
    })
  }
});

Upvotes: 0

Miaplacidus
Miaplacidus

Reputation: 545

Based on your provided configuration, it should not be possible for jQuery to perform the submit action. The jQuery selector is #surveyImage, which does not match any id attributes in the provided HTML.

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

I think you may be able to resolve the issue by using a different query selector string.

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

or...

$('form[id^="surveyImage"]').submit...

Upvotes: 0

vogomatix
vogomatix

Reputation: 5041

Why not give your forms a common class

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


$('.myClass').submit(...

Upvotes: 1

Related Questions