airi airi - 6 months ago 11
Javascript Question

Change div value based on total of several radio button value

I have several radio button in table. how javascript or jquery can add this radio button value and change the default total value without click submit button. I mean when user click a radio button it automaticly change the value in total_score div

<table>
<tr>
<td>
<input type="radio" name="evaluation_1_3" value="1">1
<br>
</td>
<td>
<input type="radio" name="evaluation_1_3" value="2">2
<br>
</td>
<td>
<input type="radio" name="evaluation_1_3" value="3">3
<br>
</td>
<td>
<input type="radio" name="evaluation_1_3" value="4">4
<br>
</td>
</tr>
<tr>
<td>
<input type="radio" name="evaluation_2_1" value="1">1
<br>
</td>
<td>
<input type="radio" name="evaluation_2_1" value="2">2
<br>
</td>
<td>
<input type="radio" name="evaluation_2_1" value="3">3
<br>
</td>
<td>
<input type="radio" name="evaluation_2_1" value="4">4
<br>
</td>
</tr>
<tr>
<td colspan="2" bgcolor="#ffffff" style=" height:;">
<div id="total_score" name="total_score" align="center">
<h3>0</h3>
</div>
</td>
</tr>
</table>


I found below coding is good but it not change automaticly the default div.

$(document).ready(function() {

var evaluation_1_1 = $('input[name="evaluation_1_1"]:checked').val();
var evaluation_1_2 = $('input[name="evaluation_1_2"]:checked').val();
var totals = parseInt(evaluation_1_1) + parseInt(evaluation_1_2);
alert(totals);
document.getElementById("total_score").innerHTML = totals;
}

Answer

You can use :radio Selector to find all the radio element then subscribe to its change event.

$(document).ready(function() {
  $(':radio').on('change', function() {
    var evaluation_1_3 = $('input[name="evaluation_1_3"]:checked').val() || 0;
    var evaluation_2_1 = $('input[name="evaluation_2_1"]:checked').val() || 0;
    var totals = parseInt(evaluation_1_3, 10) + parseInt(evaluation_2_1, 10);
    $("#total_score h3").html(totals);
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <input type="radio" name="evaluation_1_3" value="1">1
      <br>
    </td>
    <td>
      <input type="radio" name="evaluation_1_3" value="2">2
      <br>
    </td>
    <td>
      <input type="radio" name="evaluation_1_3" value="3">3
      <br>
    </td>
    <td>
      <input type="radio" name="evaluation_1_3" value="4">4
      <br>
    </td>
  </tr>
  <tr>
    <td>
      <input type="radio" name="evaluation_2_1" value="1">1
      <br>
    </td>
    <td>
      <input type="radio" name="evaluation_2_1" value="2">2
      <br>
    </td>
    <td>
      <input type="radio" name="evaluation_2_1" value="3">3
      <br>
    </td>
    <td>
      <input type="radio" name="evaluation_2_1" value="4">4
      <br>
    </td>
  </tr>
  <tr>
    <td colspan="2" bgcolor="#ffffff" style=" height:;">
      <div id="total_score" name="total_score" align="center">
        <h3>0</h3>
      </div>
    </td>
  </tr>
</table>

Comments