I have a small project in which the user writes something into an input field. Then with javascript you capitalize every second letter of an input, then show the new string on the site. Ive been trying to assign tekstEndrer.innerHTML to the new string but its not working.
const tekst = document.getElementById("tekstInput").value;
document.querySelector('input[type=button]').addEventListener("click", function(){tekstEndrer();});
const tekstEndrer = () => {
var res = "";
for (let i = 0; i < tekst.length; i++) {
res += i % 2 == 0 ? tekst.charAt(i).toUpperCase() : tekst.charAt(i);
}
document.getElementById("nyTekst").innerHTML = res;
}
<!doctype html>
<html>
<head>
<title>Tekstformatering</title>
</head>
<body>
<h1>tekst endrer</h1>
<input type="text" id="tekstInput">
<input type="button" value="Endre tekst!" id="knapp">
<div id="nyTekst"> yoyo</div>
<script type="text/javascript" src="tekstlek.js"></script>
</body>
</html>
You'll need to access the value inside the callback function for the addEventListener and then pass it in to the function as an argument as it's not going to be in scope if you do it outside of the callback:
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('input[type=button]').addEventListener("click", function(){
const tekst = document.getElementById("tekstInput").value;
tekstEndrer(tekst);
});
const tekstEndrer = (tekst) => {
var res = "";
for (let i = 0; i < tekst.length; i++) {
res += i % 2 == 0 ? tekst.charAt(i).toUpperCase() : tekst.charAt(i);
}
document.getElementById("nyTekst").innerHTML = res;
}
})
<input id="tekstInput">
<input type="button">
<div id="nyTekst"></div>