Why am I using the "jQuery click event, after adding content" method is not working

Here I am using jQuery Version 3.1.1, Why am I using this method not working?

$('input[name="images-post[]"').on("click", 'input[name="images-post[]"]', function() {
  $('.menu-create-post .mdi-camera').append('<input type="file name="images-post[]" accept="image/*" multiple="multiple">');
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="wrapper">
  <span class="span-wrapper" style="display: inline-block;">
    <input type="file" name="images-post[]"/>
  </span>
</div>
      

Run codeHide result


Correct the error: D

+3


source to share


3 answers


There are several bugs in the code.

  • Live events must be bound to static elements, so $(static).on('event', dynamic, function () {})

  • You have no elements to which you are trying to add an input element

  • append

    missing "

    aftertype="file

  • Using domReady



$(document).ready(function() {
  $(document).on("click", 'input[name="images-post[]"]', function() {
    $('.menu-create-post .mdi-camera').append('<input type="file" name="images-post[]" accept="image/*" multiple="multiple">');
  });
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="wrapper">
  <span class="span-wrapper" style="display: inline-block;">
    <input type="file" name="images-post[]"/>
  </span>
</div>
<div class="menu-create-post">
  <div class="mdi-camera"></div>
</div>
      

Run codeHide result


+3


source


Just like @Justinas said, you have a few bugs in your home. Delegating a click event is no better than a change event for file input. Btw, you have to delegate your static DOM based event to dynamic DOM.



$(function(){
    $('.span-wrapper').on("click", '[name="images-post[]"]', function() {
    $('.mdi-camera').append('<input type="file" name="images-post[]" accept="image/*" multiple="multiple">');
  });
})
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="wrapper">
  <span class="span-wrapper" style="display: inline-block;">
    <input type="file" name="images-post[]"/>
  </span>
  <span class="mdi-camera"></span>
</div>
      

Run codeHide result


+1


source


You can also make the binding event for the click and just call it whenever you need it.

function bindClick(){
     $('input[name="images-post[]"').unbind();
     $('input[name="images-post[]"').bind("click", 'input[name="images-post[]"]', function() {
         $('.menu-create-post .mdi-camera').append('<input type="file name="images-post[]" accept="image/*" multiple="multiple">');
     });
}

      

0


source







All Articles