简体   繁体   中英

script not executing for appended data but executing for prewritten html code inside form, also script is already loaded in top of page

i have a code where i on click on #add it appends some html which have unique class name with them. The code is appended something like this

<script>
    var x = 1;
    $("#add").click(function() {
        $("#form").last().append('<input name="item' + x + '" placeholder="name" type="text" class="jj' + x + '"/><input type="text" class="xx' + x + '" name="some' + x + '">');
        x = x + 1;
    });
</script>

Also i have scripts written for these classes already loaded at starting of the page

<script>
    var npp = "something";
    $(document).ready(function() {
        //o
        $(".jj").click(function() {
            $(".xx").val(npp);
        });
        //1
        $(".jj1").click(function() {
            $(".xx1").val(npp);
        });
        //2
        $(".jj2").click(function() {
            $(".xx2").val(npp);
        });
        //3
        $(".jj3").click(function() {
            $(".xx3").val(npp);
        });
    });
</script>

in console it shows no error, but also the script isn't executing for the elements added by append function, also the script is being executed for first element already present in html inside form.

<form id="form" action="..." method="post">
<input type="text" name="item" class="jj">
<input type="text" name="some" class="xx">
</form>
<button id="add">Add new field</button>

My actual is somewhat different but the basic functioning/logic is same. Kindly advice why my script isn't working.

Here is a good answer explaining your problem: Read it here with examples

And I quote:

Because those are dynamically added elements to the existing HTML, so you need to delegate it using on event handler attachment with the document.

so instead of:

$(".jj").click(function(){
  $(".xx").val(npp);
});

do:

$("body").on('click' , '.jj', function () {                
  $(".xx").val(npp);
});

And so on...

Instead of using .click function use on to be applied on any elements you add to your html code.

Example:

      $("body").on('click' , '.jj2' , function(){
        $(".xx2").val(npp);
      });  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM