2011-03-25 42 views
8

我有一個文本框,其中包含onkeyup事件。但是,當我選擇瀏覽器自動完成值時,此事件未被觸發。我添加了一個onclick事件,但它不起作用。Javascript發現瀏覽器的一些選擇自動完成值

我已經測試了很多發佈在stackoverflow上的解決方案來捕獲瀏覽autocoComplete選擇,但沒有任何解決了這個問題。

試試這個簡單的例子來看看這個問題(在Firefox 3.6,Chrome的10.0和IE8轉載):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html> 
<head> 
    <title>Test</title> 
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script> 
    <script type="text/javascript"> 
    //<![CDATA[ 
     function onkeyupInput(){ 
      $('#divResult').text($('#myInput').val()); 
     } 
    //]]> 
    </script> 
</head> 
<body> 
    <form name="myForm" action="#"> 
     Tape a value and send it. Then select this value with your browser AutoComplete value :<br /> 
     <input id="myInput" name="myInput" type="text" onkeyup="onkeyupInput();" onclick="onkeyupInput();" value="" /> 
     <input type="submit" /> 
    </form> 
    Result of onkeypress and onclick : 
    <div id="divResult"></div> 
    <br /> 
    <b>The issue : Result of onkeypress and onclick is not update when an autocomplete value of a browser is selected.</b> 
</body> 
</html> 

謝謝!

回答

8

較新的瀏覽器都支持oninput事件:

$(function() { 
    $('#myInput').on("input",function() { 
    $('#divResult').text($(this).val()); 
    }); 
}); 

<input id="myInput" name="myInput" type="text" value="" /> 

如果您需要支持舊的瀏覽器,嘗試

var tId = ""; 
function monitor() { 
$('#divResult').text($('#myInput').val()); 
} 

$(function() { 
    $('#myInput') 
    .focus(function() { 
     tId=setInterval(monitor,100); 
    }) 
    .blur(function() { 
     clearInterval(tId); 
    }); 
}); 
+0

謝謝,它的作品! – 2011-03-25 10:37:13

+0

@goby很棒 - 很高興幫助和學習過程中的東西 – mplungjan 2011-03-25 10:45:40