versatile_programmer
versatile_programmer

Reputation: 235

How do I get letters in the inputs and change writing in the div?

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">&nbsp&nbsp&nbsp<input id="i2" type="text"><br><br>
<button id="btn" class="btn btn-danger">Change</button>

Upvotes: 0

Views: 70

Answers (1)

0stone0
0stone0

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" >&nbsp&nbsp&nbsp<input id="i2" type="text"><br><br>
<button id="btn" class="btn btn-danger">Change</button>

Upvotes: 4

Related Questions