Jquery dynamically created inputs not posting

2019-09-07 02:26发布

问题:

I have a form that has inputs being created dynamically with Jquery. If I hardcode an element exactly like it is being created with Jquery, I get the POST data fine. But when the elements are created dynamically, they do not submit their POST data.

The Jquery for creating the elements (using Jquery-UI to drag and drop an element, when it is dropped it creates a new element in that area).

$(".drop-container").droppable({
    accept: ".draggable",
    addClasses: false,
    drop: function (event, ui) {
        var drag_name = ui.draggable.html();
        ui.draggable.hide();
        var new_body_count = '<tr><td class="btn btn-primary">' + drag_name + '</td><td class="badge"><input placeholder="Number of Kills" name="body_count" class="number-count" type="number"></td></tr>'
        $('.table').prepend(new_body_count)
    }
});

The HTML that it creates -

<tr>
    <td class="btn btn-primary">
        <span class="glyphicon glyphicon-resize-vertical" aria-hidden="true">
            <input type="hidden" name="actor_id[]" value="162705079">
        </span>
        Julie Benz - J
    </td>
    <td class="badge">
        <input placeholder="Number of Kills" name="body_count" class="number-count" type="number">
    </td>
</tr>

It is definitely inside of the form tag. Like I said, if I hardcode the html, it POSTS fine, but when the inputs are created by Jquery, no post. I am quite sure something to do with it being dynamically created.

edit -

$('#update_form').on('submit', 'form', function(){
     $('.abridged-hide input').attr('disabled', true);
     $('.unabridged-hide input').attr('disabled', true);
});

edit - the code for the HTML form

<legend class="text-center">Film title: <?=$film_title_text?></legend>
<div class="col-md-3">
    <?=form_open('update/add_category');?>
        <label for="category">Category Title</label>
        <?=form_input($cat_title, '');?>
        <button type="submit" class="btn btn-primary">Add Category</button> 
    <?=form_close();?>
</div>
<div id="event_form" class="col-md-6">
    <?=form_open('/update/save_entry', $update_id);?>
    <?php if(isset($thenav['nav_id'])){?>
        <input type="hidden" name="film_id" value="<?=$q?>">
        <div class="form-group">
            <label for="add_category">Add Category</label>
            <?=form_dropdown('cat_id', $cat, '', $cat_id );?>
        </div>
        <div class="form-group">
           <label for="heading">Article Title</label>
           <?=form_input($title, '');?>
        </div>
        <div class="well">
             <div class="form-group">
                  <label for="heading">Add Custom Body Count Field</label>
                  <input type="text" class="form-control" name="body_count">
                  <button class="btn btn-primary" id="custom_body_cnt">Add Custom Body Count Field</button>
             </div>     
         </div>
         <div class="panel panel-primary">
             <div class="panel-heading">Abridged Cast</div>
         <div class="panel-body abridged-hide">
    <?php 
    foreach ($this_actors as $this_actor['name']) {
        $characters = $this_actor['name']->name;
        if(isset($characters[0])){
            $characters = $characters[0];
        }else{
            $characters = '';
        }
        echo "<span class='btn btn-primary draggable'><input type='hidden' class='actor_field' name='actor_id[]' value='".$this_actor['name']->id."'><span class='glyphicon glyphicon-resize-vertical' aria-hidden='true'></span> ".$this_actor['name']->name." - ".$characters."</span>";
    }?>
        </div>
    </div>
    <button id="slide-abridged" class="btn wide-button"><span class='glyphicon glyphicon-resize-vertical' aria-hidden='true'></span></button>

    <div class="panel panel-primary">
    <div class="panel-heading">Unabridged Cast</div>
         <button id="slide-unabridged" class="btn wide-button"><span class='glyphicon glyphicon-resize-vertical' aria-hidden='true'></span></button>
        <div class="panel-body unabridged-hide">
    <?php 
    foreach ($unabridged_actors as $this_actor['name']) {
        $characters = $this_actor['name']->characters;
        if(isset($characters[0])){
            $characters = $characters[0];
        }else{
            $characters = '';
        }
        echo "<input type='text' name='actor_name' value='".$this_actor['name']->id."'>";
        echo "<span class='btn btn-primary draggable'><span class='glyphicon glyphicon-resize-vertical' aria-hidden='true'></span> ".$this_actor['name']->name." - ".$characters."</span>";
    }?>
        </div>
    </div>
    <button id="slide-unabridged" class="btn wide-button"><span class='glyphicon glyphicon-resize-vertical' aria-hidden='true'></span></button>
    <?=form_textarea($article, '');?>
    </div>
    <div class="col-md-3">
        <span class="label label-default">Body Count Inventory</span>
        <div class="well drop-container clearfix">
            <table class="table">               
                <tr>
                    <td class="btn btn-primary">Total</td>
                    <td class="badge"><input placeholder="Number of Kills" name="film_total" class="film_total" disabled type="number"></td>
                </tr>
            </table>
        </div>
       <button type="submit" id="entry_submit" class="btn btn-primary">Update Page</button>
<?php }?>

<?=form_close()?>
</div>

回答1:

I'd like to ask you for some more details, but stack overflow won't let me.

Anyways, if you're handling the POST on a submit event through jQuery, chances are that you're not binding the event to dynamically added forms.

For example, if you bind the event to forms this way:

$("form").on("submit", function(){
    //do POST stuff
})

It will only attach the event to forms that were in the DOM at the time you bind the event.

In order to bind events to dynamic elements, you must do it through a non-dynamic element. For example, let's say your forms are wrapped inside a div with id forms-container. Then you could attach the event like this:

$("#forms-container").on("submit", "form", function(){
    //do POST stuff
})

This way the event would be attached to all elements inside #forms-container, including the ones which are dynamically added.



回答2:

As I suspected, it was a delegation issue, but I still don't quite understand it.

This works -

$('#reg_form').on('submit', function(event){
    var address = $('input[name=address]').val();
    var city = $('input[name=city]').val();
    var state = $('select[name=state]').val();
    var zip = $('input[name=zip]').val();
   var format_address = address + '+' + city + '+' + state + '+' + zip;
   var password = $('input[name=password]').val();
   var password_verify = $('input[name=confirm_password]').val();
   var email = $('input[name=email]').val();
   var confirm_email = $('input[name=confirm_email]').val();
   if(email != confirm_email){
       event.preventDefault();
       $('.text-danger').show();
       $('.text-danger').html('Email Address does not match.');
  }
  if(password != password_verify)
 {
    event.preventDefault();
    $('.text-danger').show();
    $('.text-danger').html('Password does not match.');
 }
//call google maps api 
$.getJSON( "https://maps.googleapis.com/maps/api/geocode/json?address=" + format_address, function( data ) {
  console.log(data.results[0].geometry.location.lat);
  console.log(data.results[0].geometry.location.lng);
//populate form fields    
  $('input[name=lat]').val(data.results[0].geometry.location.lat);
  $('input[name=lng]').val(data.results[0].geometry.location.lng);
  });

  $(this).unbind('submit');
});

If I take out that unbind, the form does not post the dynamically generated values. I had tried a few things likes doing this in the very beginning -

$('.form_container').on('submit', 'form', function(event){

and I tried a few other things can't thing of right now..binding preventdefault, unbinding preventdefault.

But like I said, this above code with the unbind works. Maybe someone who knows about about binding and delegation more than me can weigh in on it.