I feel like I'm stupid. My English is not very good so I can't understand anything when I read solutions. I prepared a lab for you guys. Please look at it.
(Please find solution as Vanilla Javascript instead of JQuery)
HTML:
<div id = "row1">
<span>Word</span>
<span>Word2</span>
<span>Word3</span>
</div>
<input id="inputfield">
JS:
var childs = document.getElementById('row1').childNodes;
var input = document.getElementById('inputfield');
childs.forEach(e => {
if(e.innerText){
console.log(e.innerText);
input.value += e.innerText;
//simulate a key press right here (space)
//input's value have to be like this > Word Word2 Word3
}
})
The easiest way, in my opinion, is to have an array of values and use the join()
method of the array to create a string out of it. With join()
you can add a string between each word, like a space, or a letter if you want.
The snippet below loops over each <span>
element with the Array.from()
and map()
methods to turn the elements in an array and to return a new array with only the textContent
value of each <span>
. Now you have an array that looks like this.
['Word', 'Word2', 'Word3']
And by using join(' ')
on that array you can turn it into a string what spaces between each word.
var words = ['Word', 'Word2', 'Word3'];
words.join(' '); // "Word Word2 Word3"
var childs = document.querySelectorAll('#row1 span');
var input = document.getElementById('inputfield');
var words = Array.from(childs).map(child => child.textContent);
input.value = words.join(' ');
<div id = "row1">
<span>Word</span>
<span>Word2</span>
<span>Word3</span>
</div>
<input id="inputfield">
You can create your own keyboard events with the KeyboardEvent()
constructor. With this you can create your own event with the key that is supposed to be pressed. But you'll have to listen for the event as well as the browser won't know what to do with it without you telling it what to do.
With dispatchEvent()
you can fire the event from a certain element. And when you listen to that event on that element, you will catch the created event.
On your input listen for the keydown
event and check if the pressed key is the spacebar. In the example below either the key
, keyCode
and code
represent the spacebar, but in different ways.
var childs = document.querySelectorAll('#row1 span');
var input = document.getElementById('inputfield');
input.addEventListener('keydown', event => {
if (event.key === "Space" || event.keyCode === 32 || event.code === '32') {
console.log('Spacebar simulated');
input.value += ' ';
}
});
childs.forEach(e => {
if (e.innerText) {
input.value += e.innerText;
var keydownEvent = new KeyboardEvent('keydown', {
key: "Space",
keyCode: 32,
code: '32'
});
input.dispatchEvent(keydownEvent);
}
});
<div id="row1">
<span>Word</span>
<span>Word2</span>
<span>Word3</span>
</div>
<input id="inputfield">