Skip to content
Advertisement

how to set value to specific object of array object in javasript

I have to write inputbox inner a looping statement. let say I have 3 times loop

<?php
    for($i = 0; i<3;i++){
?>
      <input type="number" id="numb" onkeyup="getvalue(this.value)"/>
      <span id="result"></result>
<?php
    }
?>

<script>
function getvalue(val){
        var res= parseInt(val)*10;
        if(isNaN(res) == true){
            res = 0;
        }
        document.getElementById('result').value = res;

}
</script>

the question is, how to set every value I type in inputbox only settbthe result inner span from its row index only

Advertisement

Answer

You might have more luck trying an approach like this. Remove the ID attributes from the elements – you can replace with class names if you like or remove entirely from the span element as it should not necessarily be required to allow you to target it programmatically. If you use sibling selectors you can use the target attribtute of the event ( in this case keyup within the number element ) and then traverse the DOM to find the span…

<?php
    for($i = 0; $i<3; $i++){
?>
      <input type="number" class="numb" onkeyup="getvalue(event)"/>
      <span class="result"></span>
<?php
    }
?>

<script>
    function getvalue(e){
        var node=e.target.nextElementSibling;
        var res=parseInt(e.target.value) * 10;
        if( isNaN(res) )res=0;
        node.textContent=res;
    }
</script>

function getvalue(e){
  var node=e.target.nextElementSibling;
  var res=parseInt(e.target.value) * 10;
  if( isNaN(res) )res=0;
  node.textContent=res;
}
<input type="number" onkeyup="getvalue(event)" />
<span></span>
<input type="number" onkeyup="getvalue(event)" />
<span></span>
<input type="number" onkeyup="getvalue(event)" />
<span></span>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement