Search code examples
jqueryjquery-templates

JQuery Template Keypress event is not attached. Read Detail


I have checked in FireFox Firebug and found that Keypress event is not attached with Index textbox thus allowing everything in it.

BUT: If I move that out of template than event is attached and everthing is working properly.

Anyone got any solution?

$('#index').keypress(function (e) {
    if (e.which == 8) return true;
    if (!/[\d+]/i.test(String.fromCharCode(e.which))) return false;
});

Template

<script id="gridTemplate" type="text/x-jQuery-tmpl">
    <tr class="gridRow">
        <td class="cellTd">
            <input id="index" name="index" class="numberField" type="text" value="${IndexOrder}" />
        </td>
    </tr>

</script>



<div class="gridDiv">
<table class="gridTable" cellspacing="0" cellpadding="0">
    <tbody>
        <tr class="gridTitleRow">
            <td class="iconLink widthAuto">Sort Order</td>
        </tr>
    </tbody>
</table>
</div>

Solution

  • I think this is because the input is being added to the page late. Try binding the keypress using .live()

    $('#index').live('keypress',function (e) {
        if (e.which == 8) return true;
        if (!/[\d+]/i.test(String.fromCharCode(e.which))) return false;
    });
    

    .live() allows you to:

    Attach a handler to the event for all elements which match the current selector, now and in the future.

    from http://api.jquery.com/live/ (my emphasis)