This question already has an answer here:
- Add two functions to window.onload 12 answers
<script>
function fillText() {
var myswitch = document.getElementById("myonoffswitch");
var mytextarea= document.getElementById("mytextarea");
myswitch.onchange = function(){
if(this.checked){
mytextarea.value = "Hi there"
}else{
mytextarea.value = "Bye bye"
}
}
}
window.onload = fillText;
</script>
<input type="checkbox" id="myonoffswitch">Switch</input>
<textarea name="text" id="mytextarea" style="width:100%;resize: none;" cols="25" rows="10">
Some text 1
</textarea>
The code above shows a textarea with a switch checkbox (javascript). If you click the checkbox it will change the text in the textarea. The code above works fine. But the problem is when I try to add another one, so another switch and another textbox...
I just tried to copy paste the code with a different id name etc. but somehow it disables the first box:
<script>
function fillText() {
var myswitch = document.getElementById("myonoffswitch");
var mytextarea= document.getElementById("mytextarea");
myswitch.onchange = function(){
if(this.checked){
mytextarea.value = "Hi there"
}else{
mytextarea.value = "Bye bye"
}
}
}
window.onload = fillText;
</script>
<script>
function fillText() {
var myswitch2 = document.getElementById("myonoffswitch2");
var mytextarea2= document.getElementById("mytextarea2");
myswitch.onchange = function(){
if(this.checked){
mytextarea2.value = "Hi there"
}else{
mytextarea2.value = "Bye bye"
}
}
}
window.onload = fillText;
</script>
<input type="checkbox" id="myonoffswitch">Switch</input>
<textarea name="text" id="mytextarea" style="width:100%;resize: none;" cols="25" rows="10">
Some text 1
</textarea>
<input type="checkbox" id="myonoffswitch2">Switch</input>
<textarea name="text" id="mytextarea2" style="width:100%;resize: none;" cols="25" rows="10">
Some text 2
</textarea>
Aucun commentaire:
Enregistrer un commentaire