如何将我的事件处理与HTML代码分开

时间:2016-08-27 16:30:40

标签: javascript html arrays

我的代码工作正常,但有一种方法可以在HTML表单中没有我的事件(onclick)。如何在此使用eventlistener?

这是HTML:

<strong>Select Your fees Options</strong></label><br/>
<input type="checkbox" name="fee" id="exc" value="12000.00" onclick = "updateFee()"  required><label>PTA and Excursion and Magazine Fee N12,000.00</label><br>
<input type="checkbox" name="fee"  id="fol" value="3000.00" onclick = "updateFee()" ><label>Folder Fee <b>(optional)</b> N3,000.00</label><br>
<input type="checkbox" name="fee"  id="ext"    value="15000.00"  onclick = "updateFee()" ><label>Extra Lesson <b>(optional)</b> N15,000.00</label><br>
<input type="checkbox" name="fee"  id="clu" value="15000.00"  onclick = "updateFee()"><label>Club <b>(optional)</b> N15,000.00</label><br>
<!--total fee is here-->   
<p><b>Total Fee:
<input  name="amt" id="amt" class="form-control number" type="text" /> <br>

这是JavaScript:

<script> 
function updateFee(){
var  totFee = 0;
var fee=document.getElementsByName("fee");
for (i = 0; i < fee.length; i++)
{
if (fee[i].checked == true)
{
totFee += parseInt(fee[i].value, 10);       
}
}
amount = totFee  ;
document.getElementById("amt").value = amount;
}

谢谢!

1 个答案:

答案 0 :(得分:1)

使用javascript / jQuery

在你的情况下,它将是

<strong>Select Your fees Options</strong></label><br/>
<input type="checkbox" name="fee" id="exc" value="12000.00" required><label>PTA and Excursion and Magazine Fee N12,000.00</label><br>
<input type="checkbox" name="fee"  id="fol" value="3000.00"><label>Folder Fee <b>(optional)</b> N3,000.00</label><br>
<input type="checkbox" name="fee"  id="ext"    value="15000.00"><label>Extra Lesson <b>(optional)</b> N15,000.00</label><br>
<input type="checkbox" name="fee"  id="clu" value="15000.00"><label>Club <b>(optional)</b> N15,000.00</label><br>
<!--total fee is here-->   
<p><b>Total Fee:
<input  name="amt" id="amt" class="form-control number" type="text" /> <br>

然后,你的脚本:

使用jQuery

$(document).ready(function() {
   $('input[name=fee]').on('click', function() {
      var fee = 0;
      $('input[name=fee]:checked').each(function() {
         fee+=parseFloat($(this).val());
      });
      $('#amt').val(fee);
   });
});

或者,没有jQuery(使用updateFee函数:

// run this script after page finish loading
window.onload = function() {
    // get all the checkboxes you want to listen to
    var cbs = document.getElementsByName('fee');

    // attach click event for each one
    for(var i=0; i<cbs.length; i++) {
       cbs[i].onclick=updateFee;
    }
};