2011-07-24 25 views
3

環境: 請使用IE用於測試它的Javascript文本字段值重點

要求: 我有檢查,如果用戶輸入的值小於8位的警報消息 - 用戶將無法移動到下一個領域......他應該保持在同一個領域。

問題: 一切都很好,與除一件事的功能 - 當用戶在文本框輸入的任何值小於8位,他得到他FOUCS回以這樣的方式比光標移動到的第一個字母輸入的值,而它應該返回到輸入值的最後一個字母。

代碼:

<html> 
<body> 
<script> 
function checkField(field) { 

     if (field.value.length < 8) { 
      // Toggle the active element's blur off and back on after the next blur 
      var active = document.activeElement; 
      if (active && active !== field) { 
       var blur = active.onblur || function(){}; 
       active.onblur = function(){ active.onblur = blur }; 
      } 
      field.focus(); 
      alert("cannot be less than 8 digits"); 
     } 
    } 

</script> 
<input type="text" id="test1" onblur='return checkField(this);'> 
<br/> 
<input type="text" id="test2" onblur='return checkField(this);'> 
</tr> 
</table> 
</body> 
</html> 

回答

3

這是一個黑客,但這個工程 - 添加的onfocus聽者本身替換值,IE會通過將光標在最後的表現 - onfocus="this.value = this.value;"

像這樣來使用:

<input id="test1" type="text" value="whatever" onblur="return checkField(this);" onfocus="this.value = this.value;" /> 

如果你打算遷移到JQuery的(我推薦),看看這個插件:

// jQuery plugin: PutCursorAtEnd 1.0 
// http://plugins.jquery.com/project/PutCursorAtEnd 
// by teedyay 
// 
// Puts the cursor at the end of a textbox/ textarea 

// codesnippet: 691e18b1-f4f9-41b4-8fe8-bc8ee51b48d4 
(function($) 
{ 
    jQuery.fn.putCursorAtEnd = function() 
    { 
    return this.each(function() 
    { 
     $(this).focus() 

     // If this function exists... 
     if (this.setSelectionRange) 
     { 
     // ... then use it 
     // (Doesn't work in IE) 

     // Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh. 
     var len = $(this).val().length * 2; 
     this.setSelectionRange(len, len); 
     } 
     else 
     { 
     // ... otherwise replace the contents with itself 
     // (Doesn't work in Google Chrome) 
     $(this).val($(this).val()); 
     } 

     // Scroll to the bottom, in case we're in a tall textarea 
     // (Necessary for Firefox and Google Chrome) 
     this.scrollTop = 999999; 
    }); 
    }; 
})(jQuery); 
+0

PERFECT:d感謝 –

+0

一個變化我想提出的是後this.scrollTop = ... DO this.scrollLeft = this.scrollWidth;否則你不能總是看到光標。 – Dunc

相關問題