I have the following JS function which should change the word "hi" to "yo" on a button click if the user has input this. For example "hi, how are you today?" ==> "Yo, how are you today?"
function changeWord() {
let str = document.getElementById('inputBox').innerHTML;
document.getElementById('inputBox').innerHTML = str.replace("hi", "yo");;
}
The above doesn't work when I call changeWord(); on click, any ideas?
CodePudding user response:
You should be targeting the value of the input rather than the HTML.
const input = document.querySelector('input');
const button = document.querySelector('button');
button.addEventListener('click', changeWord, false);
function changeWord() {
const str = input.value;
input.value = str.replace("hi", "yo");
}
<input type="text" />
<button>Click</button>
CodePudding user response:
Use .value instead of .innerHTML, like this:
let str = document.getElementById('inputBox').value;
document.getElementById('inputBox').value = str.replace("hi", "yo");