nanobash
nanobash

Reputation: 5500

onkeyup event for checkbox

I have a simple situation here. lets face html code first =>

<form name="geoKey" method="post" action="index.php">
<fieldset class="gKey">
        <legend><input type="checkbox" name="checkUncheck" id="checkUncheck"></legend>
        <textarea name="txt" id="txt" cols="34" rows="5"></textarea>
</fieldset>
</form>

and here is javascript =>

function keyPress(e){
    var key;
    var box = document.getElementById("checkUncheck");
    if (window.event){
        key = event.keyCode;
    } else {
        key = e.which;
    }
    if (key==192){
        (box.checked) ? box.checked=false : box.checked=true;
    }
}

window.onload = function(){
    document.onkeyup = keyPress;
};

so , like you see guys when it is pressed key (numbered 192) checkbox is checking if it is not checked and otherwise too (this is everything working nicely) , but here is a issue => I want that if cursor is focused on textarea and pressed that key (192) in textarea doesn't write anything . please help , thanks :)

Upvotes: 0

Views: 4198

Answers (1)

Zeta
Zeta

Reputation: 105885

Use onkeydown instead and prevent the default browser action by using e.preventDefault:

function keyPress(e){
    var key;
    var box = document.getElementById("checkUncheck");
    if (window.event){
        key = event.keyCode;
    } else {
        key = e.which;
    }
    if (key==192){
        e.preventDefault(); // <-- prevent default action
        (box.checked) ? box.checked=false : box.checked=true;
        return false;
    }
}

window.onload = function(){
    document.onkeydown = keyPress;
};

JSFiddle demo.

Upvotes: 1

Related Questions