tags:

views:

345

answers:

3

Does anyone know how can I remove keypress from input with jquery?

Example:

<input type="text" keypress="cleanMsg()" id="cleanMsg" name="cleanMsg">

How can I removed the keypress="cleanMsg()" from input by using jquery? Or anyway to replace keypress="cleanMsg()" to keypress="Msg()"??

+2  A: 

I assume you mean "how do you remove the 'keypress' attribute from the input", in which case this would work

<script>
    $(document).ready(function(){
        $("#cleanMsg").removeAttr("keypress");
    });
</script>

If you want to bind to a keypress, you should do it in the jQuery way (refer to the docs), with this code the above attribute within the input tag is redundant

<script>
    $(document).ready(function(){
        $("#cleanMsg").keypress(function(){
            //do something here
        });
    });
</script>
wiifm
A: 

Doesnt work ...

$("#cleanMsg").removeAttr("keypress");   // <- doesnt work
$("#cleanMsg").removeAttr("onkeypress"); // <- doesnt work: although I expected it would ??
$("#cleanMsg").keypress(null);           // <- doesnt work: I had to kill the process!
$("#cleanMsg").keypress(function(){});   // <- works but inefficient and less than ideal ...

By ideal I mean something like ...

var cleanMsg         = document.getElementById('cleanMsg');
var originalKeypress = cleanMsg.onkeypress;
// bind new function ...
cleanMsg.onkeypress = someFunction;
function someFunction(){
  // do operations
  // unbind function ..
  cleanMsg.onkeypress = originalKeypress;
}

So has anyone worked out how to do that in jQuery coz its got me stumped?

If I work it out Ill return here n post it up.

Thanks, Eugene.

ekerner
A: 

use unbind method

$('#foo').unbind();

http://api.jquery.com/unbind/

Taha Jahangir