How can I modify this:
<script type="text/javascript">
document.onkeydown = function(event) {
if (event.keyCode === 8) {
event.preventDefault();
}
};
</script>
To allow the user to backspace in form fields on a page, but prevent them from navigating backwards by mistake?
Testing the current.target
to see if it's an input or not:
document.onkeydown = function(event) {
var key = event.keyCode || event.which,
nodeName = event.target.nodeName.toLowerCase();
if (key === 8 && nodeName !== 'input') {
alert('that\'s a nono');
event.preventDefault();
}
};
Also note the event.which
to support older browsers. But that's completely up to you of course.
You can also add other input fields like "textarea", "div", etc. depending on your requirements.
document.onkeydown = function(event) { nodeName = event.target.nodeName.toLowerCase(); if ( (event.keyCode === 8 || event.which=== 8 ) && nodeName !== 'input') { event.preventDefault(); } };
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.