I want to save the value of a week Input in a Variable.
Additionally, I want to output it in a span.
I tried this:
<input type="week" name="week" id="week-selector">
<span id="kalenderwoche"></span>
var kw = document.getElementById("week-selector").value;
document.getElementById("kalenderwoche").innerHTML = kw;
CodePudding user response:
Your code works. You just need an event handler
Here I made one that can be reused on load in case the selector has a value already
window.addEventListener("DOMContentLoaded", () => { // when page has loaded
const kw = document.getElementById("kalenderwoche");
const ws = document.getElementById("week-selector");
let kwValue; // you wanted to save it for later?
const setValue = () => kwValue = kw.textContent = ws.value || "";
ws.addEventListener("input", setValue)
setValue(); // initialise
console.log(kwValue); // saved value
});
<input type="week" name="week" id="week-selector" value="2022-W50" />
<span id="kalenderwoche"></span>
CodePudding user response:
you have to add eventListener to week input
var kw = document.getElementById("week-selector")
kw.addEventListener('change', (e) => {
console.log("e=>>>>", e.target)
document.getElementById("kalenderwoche").innerHTML = e.target.value;
})
<input type="week" name="week" id="week-selector">
<span id="kalenderwoche"></span>
CodePudding user response:
<!DOCTYPE html>
<html>
<body>
<input type="week" name="week" id="week-selector">
<span id="kalenderwoche"></span>
<script>
document.getElementById("week-selector").addEventListener('change', function() {
document.getElementById("kalenderwoche").innerHTML = this.value
})
</script>
</body>
</html>