CODE:
var appender = $('<input class="form-control" placeholder="Search" id="search_made" type="text">') appender.find('#search_made').on('keypress', function(e) { e.preventDefault() console.log('keypress!') if (e.keyCode == 13 && !e.shiftKey) { console.log('not shift enter') var passed_value = $(this).val() if (passed_value === '') { console.log('nothing was passed on input tag') return false; } console.log('passed value: ' + passed_value) } }) $('body').append(appender)
I want to add input
tag dynamically by jQuery.
Using those code, I can only add input tag seemingly but other functions that has to be bound was not bound well.
So when I type some words on input tag and click enter key
, It refreshes page but does not execute any console.log()
lines.
How can I fix it to make it do other bound functions(include console.log()
) well?
Change the selector from:
appender.find('#search_made').on('keypress', function(e) {
To
$(document).on('keypress','#search_made', function(e) {
OR: Simply
appender.on('keypress', function(e) {
Working Code Example:
var appender = $('<input class="form-control" placeholder="Search" id="search_made" type="text">') $(document).on('keypress','#search_made', function(e) { e.preventDefault() console.log('keypress!') if (e.keyCode == 13 && !e.shiftKey) { console.log('not shift enter') var passed_value = $(this).val() if (passed_value === '') { console.log('nothing was passed on input tag') return false; } console.log('passed value: ' + passed_value) } }) $('body').append(appender)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
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.