Reputation: 1
Need some help... I'm a bit of a novice and having trouble with an earlier Q&A. This tutorial is exactly what I need for my computer lab project... Original Q&A post here but when I tried to use it multiple times in my webpage it only renders the text from one input box, cancels the other out. I have changed the "ID's" so they are unique but it still won't work. Not sure if I am missing something. any help would be appreciated... Thanks in advance.
1st input:
<input type="text" id="input" /> <input type="button" onclick="updateNow()" value="Update" /> <script type="text/javascript"> function updateNow(){ document.getElementById("output").innerHTML = document.getElementById("input").value; } </script> <div id="output"></div>
2nd input:
<input type="text" id="input1" /> <input type="button" onclick="updateNow()" value="Update" /> <script type="text/javascript"> function updateNow(){ document.getElementById("output1").innerHTML = document.getElementById("input1").value; } </script> <div id="output1"></div>
Upvotes: 0
Views: 9244
Reputation: 943568
You do not get a new scope for each <script>
element (if you did, then you wouldn't be able to access them from onXXXX
attributes or load JS libraries). Consequently, each function updateNow
overwrites any previous ones. With the approach you are taking, you need a unique name for each function.
You could take a more generic approach by having a single function which identifies which button was clicked, and finds the related div by walking the DOM (e.g. by finding the output div that is inside the same div as the input).
<div>
<input class="user_input">
<input type="button" value="Update">
<div class="output"></div>
</div>
<div>
<input class="user_input">
<input type="button" value="Update">
<div class="output"></div>
</div>
<script type="text/javascript">
function updateNow(evt){
if (evt.target.type == "button") {
var div = evt.target.parentNode;
var input = div.querySelector('.user_input');
var value = input.value;
div.querySelector('.output').innerHTML = value;
}
}
addEventListener('click', updateNow);
</script>
(addEventListener
and querySelector
aren't well supported in very-old-IE. If you need to support it, then you'll have to use other approaches for binding the event listener and walking the DOM. A library like YUI or jQuery can be helpful for that.)
Upvotes: 1