This works in IE, but I cannot get it to work in Opera or Firefox. I want to prevent Backspace from navigating away if and only if the current focus is the SELECT dropdown.
<html>
<body>
<select id="testselect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<script language="javascript">
document.getElementById("testselect").onkeydown = function(e) {
if(!e) {
e = event;
}
alert(e.keyCode);
if (e.keyCode == 8 || e.keyCode == 46) {
e.returnValue = false;
e.cancelBubble = true;
if (e.stopPropagation) { e.stopPropagation(); alert("stoppropagation");}
if (e.preventDefault) { e.preventDefault(); alert("preventdefault");}
return false;
}
};
</script>
</body>
</html>
Using jquery - for only select dropdown
$(document).ready(function(){
//for IE use keydown, for Mozilla keypress
//as described in scr: http://www.codeproject.com/KB/scripting/PreventDropdownBackSpace.aspx
$('select').keypress(function(event){if (event.keyCode == 8) {return false;}});
$('select').keydown(function(event){if (event.keyCode == 8) {return false;}});
}
For all elements in page except input controls and textarea is as follows
<script type="text/javascript">
//set this variable according to the need within the page
var BACKSPACE_NAV_DISABLED = true;
function fnPreventBackspace(event){if (BACKSPACE_NAV_DISABLED && event.keyCode == 8) {return false;}}
function fnPreventBackspacePropagation(event){if(BACKSPACE_NAV_DISABLED && event.keyCode == 8){event.stopPropagation();}return true;}
$(document).ready(function(){
if(BACKSPACE_NAV_DISABLED){
//for IE use keydown, for Mozilla keypress
//as described in scr: http://www.codeproject.com/KB/scripting/PreventDropdownBackSpace.aspx
$(document).keypress(fnPreventBackspace);
$(document).keydown(fnPreventBackspace);
//Allow Backspace is the following controls
$('input').keypress(fnPreventBackspacePropagation);
$('input').keydown(fnPreventBackspacePropagation);
$('textarea').keypress(fnPreventBackspacePropagation);
$('textarea').keydown(fnPreventBackspacePropagation);
}
});
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With