Exploring the functionality of a password input field, I aim to briefly display the last character entered before reverting back to the concealed password format. Here is a snippet demonstrating this:
var showLength = 1;
var delay = 1000;
var hideAll = setTimeout(function() {}, 0);
$(document).ready(function() {
$("#password").on("input", function() {
var offset = $("#password").val().length - $("#hidden").val().length;
if (offset > 0) $("#hidden").val($("#hidden").val() + $("#password").val().substring($("#hidden").val().length, $("#hidden").val().length + offset));
else if (offset < 0) $("#hidden").val($("#hidden").val().substring(0, $("#hidden").val().length + offset));
// Update visible string
if ($(this).val().length > showLength) $(this).val($(this).val().substring(0, $(this).val().length - showLength).replace(/./g, "•") + $(this).val().substring($(this).val().length - showLength, $(this).val().length));
// Set timer for hiding characters
clearTimeout(hideAll);
hideAll = setTimeout(function() {
$("#password").val($("#password").val().replace(/./g, "•"));
}, delay);
});
});
#hidden {
opacity: 0.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="password" type="text" value="" />
<input id="hidden" type="text" value="" />
The provided code functions as intended, but there is one vexing issue:
If you enter 123456789
and attempt to delete any character in the input field, you will notice that it only removes the last character from the hidden input field (which stores data to be sent to the server).
It seems necessary to identify the position of the text cursor (which can be moved via mouse or keyboard arrow keys) in order to remove the correct character...
What steps should be taken to address this problem?
Note: Despite searching on Stack Overflow, existing codes or jQuery plugins do not adequately resolve this. A comprehensive solution is sought after.