简体   繁体   中英

How to apply javascript to element created with append()?

I have a form that appears by append(). The form contains input that need to be adjusted with with js (autocomplete function). Here is it:

function addForm() {    
<!-- function code here-->
...
html += '  <table class="form">';
html += '    <tr>';
html += '      <td>Entry product</td>';
html += '      <td><input type="text" name="product" value="" /></td>';
html += '    </tr>';
html += '    <tr>';
html += '    <td>&nbsp;</td>';
html += '    <td><div id="featured-product" class="scrollbox">';
html += '    </div>';
html += '    <input type="hidden" name="featured_product" value="" /></td>';
html += '    </tr>';
html += '  </table>';

$('#form').append(html);

}


$('input[name=\'product\']').autocomplete({
<!-- function code here-->
}

But autocomplete function doesn't work in this way. As I understand it is because of append(html) doesn't store the html to DOM. It works fine with usual html form, but i can't go this way. I need to create forms as described. So the questions are:

How can i apply js to element that are not in DOM?
Or how can I execute this elemnt to DOM with js?
Maybe I need to use smth another like append()?

Thanks.

Put this code:

$('input[name=\'product\']').autocomplete({
 <!-- function code here-->
});

after the code that appends the html. The problem is that when this bind is attempted the DOM does not contain these elements

You could also use the .on functionality to apply this:

$('input[name=\'product\']').on("autocomplete",function(){
 <!-- function code here-->
});

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