javascriptjquerybindunbind

jQuery unbind and bind keypress


I have textbox with javacript function using keypress.

<input type="text" id="statusSheet"/>

JS

$('#statusSheet').keypress(function (e)
{
    if(e.which ==13)
    {
        $('#statusSheet').unbind('keypress');

        $.ajax(
        {
            url: "chkInfo",
            type: "POST",
            data:
            {
                statusSheet: statusSheet,
                dataID: dataID
            },
            dataType: "JSON",
            success: function (jsonStr)
            {
                $('#statusSheet').bind('keypress');
            }
        }
    }
});

When I try to press enter then first it will unbind the textbox until the ajax has been processed then revert it back to bind keypress.

After tried, the unbind is working good but when revert it back, there is no effect it still unbind.

Is it possible to unbind then bind the keypress?


Solution

  • If you want to use .bind again, you have to provide an event handler. That is an action to be done when the event is being fired. You did not provided one at your re-bind attempt so nothing happens when keypress is fired.

    A solution for this is to write a function that handles your keypress event. If you want to rebind the keypress, just use that function as event handler.

    // this is called after each keypress in your element
    function handleKeyPress(e) {
        console.log('hello');
        if(e.which ==13)
        {
            console.log('unbind key. Wait 5 seconds...');
            $('#statusSheet').unbind('keypress');
    
            // this timeout replaces the ajax call (similar behavior)
            window.setTimeout(function(){
              $('#statusSheet').bind('keypress', handleKeyPress); // rebind action.
            }, 5000);
        }
    } 
    // initial bind
    $('#statusSheet').keypress(handleKeyPress);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" id="statusSheet"/>