I wrote a script that prevents the tab key from moving focus to the next field in a form and instead inserts a tab character (similar to a desktop text editor). It works perfect in Opera, partially in firefox, and not at all in chrome. Here is the code:
Code:
<script type="text/javascript">
function InsertTab(e)
{
var evtobj=window.event? event : e;
var unicode=evtobj.charCode? evtobj.charCode : evtobj.keyCode;
if (unicode==9)
{
var obj = document.getElementById('content');
if(document.selection)
{
obj.selection = document.selection.createRange();
obj.selection.text = String.fromCharCode(9);
}
else
{
var before, after;
before = obj.value.substring(0, obj.selectionStart);
after = obj.value.substring(obj.selectionEnd, obj.value.length);
obj.value= String.concat(before, String.fromCharCode(9), after);
}
if(evtobj.stopPropagation) {
evtobj.stopPropagation(); }
else {
evtobj.cancelBubble = true; }
if(evtobj.preventDefault) {
evtobj.preventDefault(); }
else {
evtobj.returnValue = false; }
}
return false;
}
function tablistener(){document.getElementById('content').addEventListener('keypress', InsertTab, true);}
window.onload=tablistener;
</script>
As I mentioned earlier, this works as expected in Opera. In firefox the tab character is inserted, but focus is still moved to the next field. In chrome no tab character is inserted and focus is still moved to the next field.
Using the code you posted, tabs are being inserted, but focus is stilled moved to the next field. I think the problem has something to do with preventDefault() not working. e.cancelable is returning true in FF, so I know its being called, it just doesn't seem to prevent the default action from occuring.
Bookmarks