Lymuel
Lymuel

Reputation: 58

jquery events not triggered if dom is populated via jquery or ajax

just want to ask if someone has done a workaround regarding jquery events not being called when field is created using jquery or ajax.

I have a date field in which works fine if it coded using the default html code. What I want to do is I can add as many dates as i want but the .datepicker() event was not triggered if it is created using jquery.

Here is my code:

<!doctype html>
<html>
    <head>
        <title>Test</title>
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>
    <body>
        <div class = "date_fld">
            <p>Date: <input type="text" id="datepicker"></p>
        </div>
        <br/>
        <br/>
        <button class = "add">Add new Date</button>
    </body>
</html>
<script>
    $(function(){
        $( "#datepicker" ).datepicker();
     });
     $(document).on("click", ".add", function(){
        $(".date_fld").append('<p>Date: <input type="text" id="datepicker"></p>');
     });
</script>

Any help would be much appreciated.

Upvotes: 1

Views: 243

Answers (4)

Marie
Marie

Reputation: 2217

You could assign the new object to a variable, append it, then initialize the datepicker to get around having to search the DOM for the newly created element first.

 $(document).on("click", ".add", function(){
    var newDatePicker = $('<p>Date: <input type="text"></p>');
    $(".date_fld").append(newDatePicker);
    newDatePicker.datepicker();
 });

Upvotes: 0

Frank Leal
Frank Leal

Reputation: 206

if the above answers doesnt work for you, just FYI u can use this code i use when everything fails.

function loadjsfile(filename){
    var fileref=document.createElement('script');
    fileref.setAttribute("type","text/javascript");
    fileref.setAttribute("src", filename);
    if (typeof fileref!="undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref);
}

loadjsfile("myscript.js") //dynamically load and add this .js file

This code will make your html load a js file inside.

Upvotes: 0

Rando
Rando

Reputation: 473

You shouldn't really be appending multiple elements with the same Id to the dom. You could have an increasing variable to run something like the following

<script>
  var x = 0;
  $(document).on("click", ".add", function(){
    $(".date_fld").append('<p>Date: <input type="text" id="datepicker' + x + '"></p>');
    $( "#datepicker" + x ).datepicker();
    x++;
  });
</script>

Upvotes: 1

Vlam
Vlam

Reputation: 1798

Have you tried the following:

<script>
     $(document).on("click", ".add", function(){
        $(".date_fld").append('<p>Date: <input type="text" id="datepicker"></p>');
        $( "#datepicker" ).datepicker();

     });
</script>

Upvotes: 0

Related Questions