-1

My motive is to have the viewer believe that a certain string is being entered as input (by displaying it in the input field, character by character, with every key press) no matter what the actual input is.The said actual input must remain unmodified and available for further use. i tried thinking in the direction of modifying the password field to show the sequence of characters that i want instead of a dot or asterisk, but apparently it is not doable. What i'm trying to achieve is exactly like the "petition" field on the site www.peteranswers.com

1 Answers1

1

Something like this?

Something like this?

I was able to accomplish this fairly easily using event listeners and event keys. Assuming the existence of an input field with the id "my_input", we can do the following:

let string = 'Hello, World! ' // The "fake" input string
string = string.split(""); // Split string into array for easy indexing

let user_input = '';

let my_input = document.getElementById('my_input'); // Input field

my_input.onkeypress = function (e) {
    e.preventDefault();

    // Get the key pressed in string form so we can play with it
    let keypress_string = String.fromCharCode(e.keyCode);

    if (/[a-zA-Z0-9-_ ]/.test(keypress_string)) { // If alphanumeric
        this.value += string[user_input.length % string.length];
        user_input += keypress_string;
    }
}

my_input.onkeydown = function (e) {
    if (e.keyCode === 8) { // If backspace
        user_input = user_input.slice(0, -1) // Chop off the last character in the string
    }
}

In this case, the actual string the user inputs will be stored in the variable user_input