Reputation: 235
I tried code snippet below entering i in the first and x in the second input but Change this writing
didn't change into Change thxs wrxtxng
Any help would be much appreciated!
var d = document.getElementById("d").innerHTML
var Btn = document.getElementById("btn");
var inp1 = document.getElementById("i1").value;
var inp2 = document.getElementById("i2").value;
Btn.addEventListener("click",change);
function change() {
var yeni = d.replaceAll(inp1,inp2);
document.getElementById("d").innerHTML = yeni;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div id="d">Change this writing</div><br>
<input id="i1" type="text">   <input id="i2" type="text"><br><br>
<button id="btn" class="btn btn-danger">Change</button>
Upvotes: 0
Views: 70
Reputation: 43962
If you place console.log(inp1, inp2);
inside the change
function, you'll see that there don't hold the expected value.
You're defining them before the user has any time to insert the value.
Easiest fix would be to call getElementById
inside the function when the button is pressed:
var Btn = document.getElementById("btn");
Btn.addEventListener("click",change);
function change() {
var inp1 = document.getElementById("i1").value;
var inp2 = document.getElementById("i2").value;
var d = document.getElementById("d");
var yeni = d.innerHTML.replaceAll(inp1, inp2);
d.innerHTML = yeni;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div id="d">Change this writing</div><br>
<input id="i1" type="text" >   <input id="i2" type="text"><br><br>
<button id="btn" class="btn btn-danger">Change</button>
Upvotes: 4