2017-06-15 41 views
-2

我有一個html輸入文本,當用戶嘗試輸入時,我只想顯示最後3個值並將其他值作爲密碼。如何僅顯示輸入中的最後3個值

是這樣的:***** 456

你有關於如何實現這一點使用JavaScript或jQuery的任何想法?

在此先感謝。

+3

你試過什麼嗎?如果您發佈了一些代碼並告訴我們您有多遠,我們可以提供幫助。 – Utkanos

+0

嘗試在jquery中使用「onKeyUp」事件的搜索結果:) – Beri

回答

0

決定刺傷它。不知道我是否真的會用這個想法...

function attachToInput(input) { 

    // the actual characters 
    var chars = []; 

    // update the input with the hidden prefix version 
    function updateInputValue() { 
    var value = chars.join(""); 
    var nHidden = Math.max(0, value.length - 3); 
    var last3 = value.substr(nHidden); 
    input.value = "*".repeat(nHidden) + last3; 
    } 

    // standard characters 
    input.addEventListener("keypress", function (e) { 
    var pos = input.selectionStart; 
    var char = String.fromCharCode(e.keyCode); 
    chars.splice(pos, 0, char); 
    updateInputValue(); 
    e.preventDefault(); 
    }); 

    // backspace & delete 
    input.addEventListener("keydown", function (e) { 
    var pos = input.selectionStart; 
    if (e.keyCode === 8) { 
     chars.splice(pos - 1, 1); 
     updateInputValue(); 
     e.preventDefault(); 
    } 
    if (e.keyCode === 46) { 
     chars.splice(pos, 1); 
     updateInputValue(); 
     e.preventDefault(); 
    } 
    }); 
} 

$(function() { 
    var input = document.getElementById("foo"); 
    attachToInput(input); 
}); 
相關問題