Skip to content Skip to sidebar Skip to footer

Need Help In Onchange Event Javascript

I have five text fields which are mark1, mark2, mark3, mark4 and total. I have a problem to make the total automatically display in the text field. I have no problem with the calcu

Solution 1:

Daisy, something like this should work. You can view a live demo of this code on JSBin.

<inputtype="text"name="mark1"id="mark1"value="" /><inputtype="text"name="mark2"id="mark2"value="" /><inputtype="text"name="mark3"id="mark3"value="" /><inputtype="text"name="mark4"id="mark4"value="" /><inputtype="text"name="total"id="total"value="" /><!-- Script block must come AFTER the input elements --><scripttype="text/javascript">var m1    = document.getElementById('mark1'),
      m2    = document.getElementById('mark2'),
      m3    = document.getElementById('mark3'),
      m4    = document.getElementById('mark4'),
      total = document.getElementById('total');

  functioncalculate_total(){
    // Use your real calculation here
    total.value = Number(m1.value) + Number(m2.value) + Number(m3.value) + Number(m4.value);
  }

  if( window.addEventListener ) {
    m1.addEventListener('change', calculate_total, false);
    m2.addEventListener('change', calculate_total, false);
    m3.addEventListener('change', calculate_total, false);
    m4.addEventListener('change', calculate_total, false);
  } elseif(window.attachEvent){
    m1.attachEvent('onchange', calculate_total);
    m2.attachEvent('onchange', calculate_total);
    m3.attachEvent('onchange', calculate_total);
    m4.attachEvent('onchange', calculate_total);
  }
</script>

UPDATE: Since you want a letter grade entered (A, B, C, F, etc) I would recommend a select control instead of an input[type='text']. One of the grade fields would look like this:

<selectname="mark1"id="mark1"><optionvalue="">Select Grade</option><optionvalue="100">A</option><optionvalue="90">B</option><optionvalue="80">C</option><optionvalue="70">D</option><optionvalue="50">F</option></select>

You put the number value in the value= portion, but you can display the friendlier A, B, C, etc.

And anywhere there was .value replace with .selectedValue (Except total.value of course).

Solution 2:

Daisy, Doug provided a great answer, but after reading your comment I thought I would contribute a small change. Note the grades array of values and the small change to Doug's function:

// Add grades and corresponding value belowvar grades = {A:100,B:70};

function calculate_total(){
  // Use your real calculation here
  total.value = grades[m1.value] + grades[m2.value] + grades[m3.value] + grades[m4.value];
}

Post a Comment for "Need Help In Onchange Event Javascript"