简体   繁体   中英

using keypress event in javascript

i want to delete php session variable using a key press. so i used these codes,

    <script type="text/javascript">
function textsizer(e){
var evtobj=window.event? event : e 
var unicode=evtobj.charCode? evtobj.charCode : evtobj.keyCode
var actualkey=String.fromCharCode(unicode)
if(actualkey=="x"){
    location.href="biling.php?cmd="+actualkey;}
}
document.onkeypress=textsizer
</script>
<?php if(isset($_GET['cmd'])){
unset($_SESSION["bill_array"]);
header('location:biling.php');
}
?> }

but the problem is, this code also clearing the session when i'm typing "x" in a text box. so i just want to stop that and clear the session only when i press "x" out side of a text box

You can check the e.target property to identify which element trigger the keypress event.

//Does not work on IE
window.addEventListener('keypress', function(e){ console.log(e.target) }, false)

Taking action when e.target.tagName == 'BODY' is a good choice.


Update

For more info about Event , check:

I think you can edit your existing function as such:

function textsizer(e) {
    var evtobj=window.event? event : e;
    var element = evtobj.target ? evtobj.target : evtobj.srcElement;
    if (element.tagName.toLowerCase() == "body") {
        var unicode=evtobj.charCode? evtobj.charCode : evtobj.keyCode;
        var actualkey=String.fromCharCode(unicode)
        if(actualkey=="x"){
            location.href="biling.php?cmd="+actualkey;
        }
    }
}

$("input[type='text']").keypress(function(){

});

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