Reputation: 23
I want to listen to input and when space is clicked with javascript, the word that is before the space, will be wrapped to look like a tag.
It should be like the "Tags" below in the "Ask a public question". code so far:
html:
<label for="subtypes" id="subtypes_label"><b>Restaurant subtypes</b></label>
<textarea type="text" name="subtypes" class="form-control w-50 p-3" id="subtypes" autocomplete="off" oninput=""></textarea>
javascript:
document.getElementById('subtypes').addEventListener('input', function(evt){
wrapSubtypes(this.value);
});
function wrapSubtypes(value){
}
I don't know what to put in the wrapSubtypes(value)
.
Thanks for the help.
Upvotes: 0
Views: 75
Reputation: 74738
May be you want to return a wrapped text in an element from the function like:
return `<span class="tag">${value.trim().split(/\s/).pop()}</span>`
document.getElementById('subtypes').addEventListener('input', function(evt) {
if (evt.data === ' ') {
let tag = wrapSubtypes(this.value);
document.getElementById('tags').innerHTML += tag;
}
});
function wrapSubtypes(value) {
return `<span class="tag">${value.trim().split(/\s/).pop()}</span>`
}
#tags{ padding:10px; }
.tag {
border-radius: 25%;
color: #444;
background: #e5e5e5;
padding:5px;
margin-right:10px;
}
<div><label for="subtypes" id="subtypes_label"><b>Restaurant subtypes</b></label>
<textarea type="text" name="subtypes" class="form-control w-50 p-3" id="subtypes" autocomplete="off"></textarea>
</div>
<div id="tags"></div>
Upvotes: 1
Reputation: 2146
Try this one:
document.getElementById('subtypes').addEventListener('input', function(evt){
wrapSubtypes(this.value);
});
function wrapSubtypes(value){
if(value.includes(' ')) {
let newElement = `<li>${value.trim()}</li>`;
document.querySelector('ul').innerHTML += newElement
document.getElementById('subtypes').value = ""
}
}
<label for="subtypes" id="subtypes_label"><b>Restaurant subtypes</b></label><br>
<textarea type="text" name="subtypes" class="form-control w-50 p-3" id="subtypes" autocomplete="off" oninput=""></textarea>
<p>Tags:</p>
<ul>
</ul>
Upvotes: 0