Home > database >  How to apply javascript functionality to ajax inserted html
How to apply javascript functionality to ajax inserted html

Time:09-22

I have a page that requests the user to input a time via selecting the time from a pop-up.

php:

<div >
    <label >Coaching Start Time</label>
    <div >
        <input  type="text" id="timepicker" name="timepicker[]" placeholder="Enter Time" />
    </div>
</div>

javascript:

<script type="text/javascript">
$(document).ready(function() {

    /* setting time */
    $("#timepicker").datetimepicker({
        format : "HH:mm"
    });
});
</script>

I want the possibility to select and submit multiple time values, so via ajax, I'm inserting copies of the php code into the page.

Ajax Call from main page:

//Once add button is clicked
$(addButton).click(function() {
    //Check maximum number of input fields
    if (x < maxField) {
        x  ; //Increment field counter
        var sd = document.getElementById("hired_date").value;
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
                $(wrapper).append(this.responseText);
            }
          }
        }
        xmlhttp.open("GET", "get_schedule_options.php?sd="   sd, true);
        xmlhttp.send();
        return false;
    }
});

Relevant ajax php code:

echo '<div >
    <label  for="Old">Coaching Start Time</label>
    <div >
        <input  type="text" id="timepicker" name="timepicker[]" placeholder="Enter Time" />
    </div>
</div>';

However, the functionality is lost because the javascript code is applied at a timing before the ajax inserts the extra html code. How can I go about applying javascript functionality to ajax inserted code?

CodePudding user response:

Add the same code after you append the response in your HTML. And make sure you use class selector instead of id. After this -

$(wrapper).append(this.responseText);

Add this -

 $(".timepicker").datetimepicker({
        format : "HH:mm"
    });

And input tag must contain class with timepicker i.e.

<input  type="text"  id="timepicker" name="timepicker[]" placeholder="Enter Time" />
  • Related