最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

asp.net - My javascript code not working in mozilla firefox - Stack Overflow

programmeradmin1浏览0评论

This is my code for making textbox accept number only.

<asp:TextBox ID="txtRotationNo" runat="server" onkeydown="return NumberOnly();" CssClass="textbox"></asp:TextBox>

function NumberOnly () {
    if(!(event.keyCode>=48 && event.keyCode<=57) && event.keyCode!=8) {
        event.returnValue=null;
    }
}

This code is working in Chrome and Opera, but not in firefox.

Can you tell me what's wrong with this code?

This is my code for making textbox accept number only.

<asp:TextBox ID="txtRotationNo" runat="server" onkeydown="return NumberOnly();" CssClass="textbox"></asp:TextBox>

function NumberOnly () {
    if(!(event.keyCode>=48 && event.keyCode<=57) && event.keyCode!=8) {
        event.returnValue=null;
    }
}

This code is working in Chrome and Opera, but not in firefox.

Can you tell me what's wrong with this code?

Share Improve this question edited May 27, 2010 at 9:26 Jan Hančič 53.9k17 gold badges98 silver badges101 bronze badges asked May 27, 2010 at 9:23 Vibin JithVibin Jith 9313 gold badges16 silver badges34 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 8

Many things wrong with the code, including the lack of an event argument, plus the wrong way about cancelling the event. Here, just replace the code with this:

function NumberOnly(e) {
  e = e || window.event; // remove this if you don't need IE support
  if (!(e.keyCode >= 48 && e.keyCode <= 57) && e.keyCode != 8)
    e.preventDefault();  // standard method of cancelling event
  return false;          // IE method of cancelling event
}

Firefox needs the event within the call of the handler and it needs to return "false" to ignore an action. This code might work:

function NumberOnly(event) {
  if(!(event.keyCode>=48 && event.keyCode<=57) && event.keyCode!=8) {
    event.returnValue=null;
    return false;
  }
}

But I think you can skip the event.returnValue=null;

On the contrary to IE, 'event' is not a global variable in Firefox. So you've got to pass the desired pressed key informations as an argument.

find the list of javascript validation function here,quite handy during development.

Thanks,

Ashish Chotalia

发布评论

评论列表(0)

  1. 暂无评论