tags:

views:

25

answers:

3

How do I update the text in the id="b"?

<script type="text/javascript">
function updateb()
{
var a= document.getElementById("a").value;
var b = document.getElementById("b").innerHTML = a * 10;
}
</script>

<input type="text" id="a" name="a" value="10" onKeyUp="updateb();" /><p id="b" name="b"></p>
<input type="text" id="a" name="a" value="20" onKeyUp="updateb();" /><p id="b" name="b"></p>
<input type="text" id="a" name="a" value="30" onKeyUp="updateb();" /><p id="b" name="b"></p>
A: 

Note that an id field must be unique to a document. That is, you can't have three elements with the same ID as in your example.

Otherwise, the code you posted should update the contents of B, though obviously you'd need to do this in response to an onchange or onblur event on the input field.

thomasrutter
+1  A: 

1.) IDs should be always unique in a page.

2.) GetElementById always returns only one element with same id if there are multiple ids with same value

3.) for above question you can try getElementsByName. it is quite similar to getElementById with a diff that it will give u all elements with same name. if you do

x= document.getElementsByName("b");

x[0] will contain first one

x[1] will contain 2nd one

x[2] will contain 3rd one

If you want it be done by getElementById then change ur elements id with any other unique name like:

<script type="text/javascript">
function updateb(Src)
{
    var a= Src.value;
    document.getElementById("b" + Src.id.substr(1)).innerHTML = a * 10;
}
</script>

<input type="text" id="a1" name="a" value="10" onKeyUp="updateb(this);" /><p id="b1" name="b"></p>
<input type="text" id="a2" name="a" value="20" onKeyUp="updateb(this);" /><p id="b2" name="b"></p>
<input type="text" id="a3" name="a" value="30" onKeyUp="updateb(this);" /><p id="b3" name="b"></p>
KoolKabin
A: 

As others have pointed out, all elements in a document should have a unique id. In your case, however, an id may not be required at all, as you can use the relative positions of elements to achieve your aims. This example doesn't need an id or a name, but this may differ in your case, depending on your overall requirements.

<script type="text/javascript"> 
    function updateb(inputElement) 
    { 
       var a = inputElement.value; 
       var target = inputElement.nextSibling;
       if(target != null){
           target.innerHTML = a * 10; 
       }
    } 
</script> 

<input type="text" value="10" onKeyUp="updateb(this);" /><p></p> 
<input type="text" value="20" onKeyUp="updateb(this);" /><p></p> 
<input type="text" value="30" onKeyUp="updateb(this);" /><p></p> 

Using a solution like the one offered by @KoolKabin may be better in the long run, as it is more tolerant to changes in the HTML structure. Either way, there are usually several different ways to approach any given problem, and you should evaluate the best for the circumstances.

belugabob