Search code examples
javascriptarrayscodeigniter-2

how to add array values in text box


I have three text box that given as an array, I want to add two text box and get a result in the third text box as shown in below.

<tbody>
   <?php 
     $i=1;
     foreach ($sub as $row) 
     {
   ?>
<tr>
<td><?php echo $i++;?>
</td>
<td>  <div><span style="border: none;"><input type="text" name="subject[]" class="textbox" value="<?php echo $row->subject_name;?>"></span></div></td>
<td><input type="text" name="mark-1[]" value="" id="mark1"></td>
<td><input type="text" name="mark-2[]" value="" id="mark2"></td>
<td><input type="text" name="total-mark[]" value="" id="totmark"  onclick="add_number()"></td>
</tr>
<?php  }  ?>
<tr>
<th colspan="4">Total Mark</th>
<td></td></tr>
</tbody>

i have used the below script and its running but getting a result in the first loop

 <script type="text/javascript">
function add_number() {
var first_number = parseInt(document.getElementById("mark1").value);
var second_number = parseInt(document.getElementById("mark2").value);
var result = first_number + second_number;
document.getElementById("totmark").value = result;
 }
</script>

please help us get an answer


Solution

  • html

    <tbody>
       <?php 
         $i=1;
    $k=1;
         foreach ($sub as $row) 
         { $k++;
       ?>
    <tr>
    <td><?php echo $i++;?>
    </td>
    <td>  <div><span style="border: none;"><input type="text" name="subject[]" class="textbox" value="<?php echo $row->subject_name;?>"></span></div></td>
    <td><input type="text" name="mark-1[]" value="" id="mark1-<?php echo $k;?>"></td>
    <td><input type="text" name="mark-2[]" value="" id="mark2-<?php echo $k;?>"></td>
    <td><input type="text" name="total-mark[]" value="" id="totmark-<?php echo $k;?>"  onclick="add_number(<?php echo $k;?>)"></td>
    </tr>
    <?php  }  ?>
    <tr>
    <th colspan="4">Total Mark</th>
    <td></td></tr>
    </tbody>
    

    Script

       <script type="text/javascript">
    function add_number(k) {
    var first_number = parseInt(document.getElementById("mark1-"+k).value);
    var second_number = parseInt(document.getElementById("mark2-"+k).value);
    var result = first_number + second_number;
    document.getElementById("totmark-"+k).value = result;
     }
    </script>