简体   繁体   中英

onKeydown is not working when added dynamically

I am trying to append some html in my web page using jQuery. My code is

 var s1 = "<div class='controls'><label class='inline labelspace'>Minimum Cart Value<input class='inline input-small' type='text' name='mincart' onKeydown=isNumberKey ></input></label>";
s1 += "<label class='inline labelspace'>Minimum No Of Items<input class='inline input-small' type='text' placeholder='Enter Integer' name='minitem' onKeydown=isNumberKey></input></label>" ;
s1 += "<label class='inline labelspace'>Location<input class='inline input-small' type='text' name='location' ></input></label>";
s1 += "<label class='inline labelspace'>Product Ids<input class='inline input-small' onKeydown=isValid type='text' name='products'></input></label></div>" ;
$("#lastrow").before(s1);

isNumberKey is a function whose source code is

function isNumberKey(evt) {
  console.log('coming to this');
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    } else 
        return true;

}

Using these function, only numbers can be entered in the text box. When I assign some element like this $("#some_elem").onKeyDown(isNumberKey) then it is working correctly but i want to know why its not working in first case.

You have to delegate the event. Use :

$(document).on('keydown' , '.some-class', isNumberKey);

If you append new elements to your markup, the event wont be binded on them. So you need to delegate it.

Use a class instead of a id . Of course the class need to be added to the appended div or , in this case, to the input I guess.

If you use $('.some-class').on('event', function(){}) the event will be attached only on existing elements that have .some-class . Using delegation will attacch the event on any div you want.

如果你想在HTML中伴随,请尝试更改下面的代码

onKeydown="isNumberKey()"

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