var test = document.getElementById("start").innerHTML;
document.getElementById("submit").onclick = function()
{
var textinput = document.getElementById("inputbox").value;
console.log(textinput)
if(textinput.charAt(0) == test.slice(-1) )
{
document.getElementById("start").innerHTML = document.getElementById("start").innerHTML.replace(test,textinput)
}
}
I am trying to figure out why whenever I press the button on my html site I only get the if statement to run once. My goal is to swap a piece of text on my html site every time the last letter is the same as the first letter of whatever text is written inside of an input box and the button is pressed but it only works for one button press for some reason
It's because you declare var test = document.getElementById("start").innerHTML; outside of the onclick function. So it is only run once and its value is never updated.
Put it inside the function to get its new value every time you press the button.
document.getElementById("submit").onclick = function(e) {
e.preventDefault();
const textinput = document.getElementById("inputbox").value;
const test = document.getElementById("start").innerHTML;
console.log(textinput)
if (textinput.charAt(0) == test.slice(-1)) {
document.getElementById("start").innerHTML = document.getElementById("start").innerHTML.replace(test, textinput)
}
}
<span id="start">Somebody once told me the world is gonna roll me</span>
<form>
<input type="text" id="inputbox" />
<button id="submit">Submit</button>
</form>