Ralanyo
Ralanyo

Reputation: 61

How to access dynamic id tag with jquery

I'm trying to update the paragraph tag in foreach with jquery selector in my second ajax call. I made the id tag unique by setting it to id="spots_,+item.id" but don't know how to access the dynamic id tag outside the foreach loop. I keep getting "id is not defined" error. Thought maybe a global variable would work but no success.

//ajax form the get available times to play
$('#form').submit(function(){
$.ajax({
  url: $('#form').attr('action'),
  type: 'POST',
  data : $('#form').serialize(),
     success: function(response){
      $.each(JSON.parse(response), function(i, item) {
          var jdate = $('#date').val();

        $('<tr>').html("<td>" + item.time + "</td><td>" + '<form class="insideForm" action="/reservations/getSpots" accept-charset="utf-8"  method="">'  + '<input type="text" name="jtime" value="' + item.time + '"' + "/>"  + '<input type="text" name="jdate" value="' + jdate + '"' + ">" + '<input type="submit" class="btn btn-primary" value="Spots">' +  '</form>' + "</td><td>" + "Spots:" + '<p class="spots" id="spots_' + id + '"'+ ">" + '<div id="spots"></div>' + '</p>'  +  "</td>").appendTo('#availableTimes');
        });//end loop                   

    //ajax form the get available spots/seats 
$('.insideForm').submit(function(){
var form = $(this).closest('form');

$.ajax({
  url: $(this).attr('action'),
  type: 'POST',
  data : $(this).serialize(),
          success: function(response){        
        $('#spots_'+id).html(response);         
      }//end success      
    });
   return false;
});                    
  }//end success
});
return false;
});//end ajax time form

Upvotes: 0

Views: 167

Answers (2)

user9263373
user9263373

Reputation: 1074

In your $.ajax call change url: $(this).attr('action') to url: form.attr('action'). Inside the callback, $(this) refers to the jqXHR object of the ajax call, not the element the event handler was bound to.

EDIT

I also changed $(this).serialize() to form.serialize() for the same reason above.

//ajax form the get available spots/seats 
$('.insideForm').submit(function() {
  var form = $(this).closest('form');

  $.ajax({
    url: form.attr('action'),
    type: 'POST',
    data: form.serialize(),
    success: function(response) {
      $('#spots_' + id).html(response);
    } //end success      
  });
  return false;
});

Upvotes: 1

In your .insideForm object you only have one .spots classed paragraph.

Try using the jQuery selector inside the form:

$('.insideForm').submit(function () {
    var form = $(this).closest('form');

    $.ajax({
        url: form.attr('action'),
        type: 'POST',
        data: form.serialize(),

        success: function (response) {
            $('.spots', form).html(response);
        }//end success

    });
    return false;
});

Upvotes: 1

Related Questions