Home > Software design >  HTML5 JavaScript, How can I clear my input field every time I hit the spacebar so there is only ever
HTML5 JavaScript, How can I clear my input field every time I hit the spacebar so there is only ever

Time:01-05

I have 2 input fields where the second is a copy of the first using this code.

window.onload = function() {
    var src = document.getElementById("paragraph-text"),
    dst = document.getElementById("copy");
    src.addEventListener('input', function() {
        dst.value = src.value;
    });
};

For every key I press when filling the first field, it shows up in the second filed. However, I'd like to have only 1 word show up at a time in the second (copy) field, meaning I want the field to clear every time I hit the spacebar (or keycode 32). Could someone help me out please.

It probably doesn't matter but here are the 2 html fields:

<input type="text" id="paragraph-text" name="paragraph-text" placeholder="type here to begin...">
<input type="text" id="copy" name="copy">

I tried this in the JavaScript:

window.onload = function() {
    var src = document.getElementById("paragraph-text"),
    dst = document.getElementById("copy");
    src.addEventListener('input', function() {
        dst.value = src.value;
        window.onkeydown = function(event) {
            if (event.keyCode == 32) {
                src.value  = ' '
                dst.value = ''
                if(event.preventDefault) event.preventDefault();
                return false;
            }
        }
    });
};

and it works except for the fact that when I type the next word, the original word is still there, so if i type a long sentence, the copy field will still contain all the words from the paragraph-text field, even though it does clear temporarily with every spacebar press. I would like it to stay cleared so the next word is alone, and so on. There should only ever be 1 word or nothing in the copy field.

CodePudding user response:

I'm not a 100% sure I understand what you actually want, but I think this might be what you're after?

window.onload = function() {
    var src = document.getElementById("paragraph-text"),
    dst = document.getElementById("copy");
    src.addEventListener('input', function() {
        dst.value = src.value.split(' ').pop();
    });
};

The first input might contain a word, or a sentence containing multiple words separated by whitespaces.

The second input should contain the last word from the first input.

We convert the contents of the first input to an array of words using split(' ') and then pop() to return the last item.

  • Related