2015-04-07 32 views
0

我想通過一個簡單的代碼通過JavaScript提交一個表單。當用戶按輸入鍵表格應提交。ascii輸入鍵返回0通過在Firefox中的JavaScript

我的代碼適用於Chrome,safari和ie,但它不適用於FireFox。這是更好地說則charCode從事件對象返回屬性0,而不是13

在Chrome JS工程和其他人:在FireFox上

var up = document.getElementById('up'); 
    var handler = function(e){ 
     if(e.charCode == 13){ 
      document.getElementById("sendForm").submit(); 
     } 

    } 
    up.keypress = addEventListener('keypress',handler); 

JS工程

var up = document.getElementById('up'); 
     var handler = function(e){ 
      if(e.charCode == 0){ 
       document.getElementById("sendForm").submit(); 
      } 

     } 
     up.keypress = addEventListener('keypress',handler); 

HTML

<form method="POST" id='sendForm' action='http://google.com'> 
    <textarea rows="4" cols="50" id='up'></textarea> 
    <input type='submit' name='sub'> 
</form 

回答

4

請勿使用keypress和e.charCode使用keydown和e.keyCode。這將使您在「Enter」的所有瀏覽器中都達到「13」。

+0

嗯,這是工作!謝謝:),但爲什麼?因爲第一個ascii代碼燒了然後keycode :) –

+0

當你需要獲得用戶鍵入的鍵的實際字符時,你使用charCode。跨瀏覽器的非字符鍵不是標準配置。 – Vic

+0

另外,如果它適合您,請接受答案。 :) – Vic