简体   繁体   中英

jQuery - Event that captures creation of dynamically created text boxes

Does jQuery have an event that will capture the creation of dynamically created DOM content? Or is there some way of doing this in jQuery?

The web page in which I am injecting jQuery into creates text boxes dynamically. I have no control over that. I would however like to check every 3 seconds whether a new text box has been created and then populate it with a value.

The text boxes look like the following:

<input id="AplEducationTbl:EstName:0" type="text" onchange="return false">
<input id="AplEducationTbl:EstName:1" type="text" onchange="return false">

So there are a couple of problems. The id uses a colon, which I don't know how to escape in jQuery. The onchange returns false, which prevents me from hooking on my events.

Using:

 setTimeout(function(){
      /* What do I put here? */
  }, 3000);

Can you use event delegation and search for IDs starting with AplEducationTbl:EstName ?

$(document).on("change", "input[id^=AplEducationTbl\\:EstName]", function() {
    console.log("Change");
});

jsFiddle

I would however like to check every 3 seconds whether a new text box has been created

To this you have to use setInterval() method instead:

var len = $('input[id^="AplEducationTbl:EstName"]').length;
setInterval(function () {
   if ($('input[id^="AplEducationTbl:EstName"]').length > len) {
      console.log('changed.');
      len = $('input[id^="AplEducationTbl:EstName"]').length; 
   }  //^^^^----------------------------------------update the value of len
}, 3000);

The id uses a colon, which I don't know how to escape in jQuery.

For this either you can use two forward slashes \\\\ as suggested by other answer and other way to use a string representation put that id value in quotes like this:

$('input[id^="AplEducationTbl:EstName"]')
//-----------^-----------------------^------put the value in quotes like this 
//------------------------------------------and you are good to go.

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