lemonginger
lemonginger

Reputation: 345

How to calculate a form field dynamically using jQuery?

I have two form fields, lets call them numerator and denominator. I want a third field, the total, to be updated automatically every time one of those values is changed (it already gets calculated in the database correctly when the form is submitted). I can grab the values of the fields using jQuery just fine, but they seem to stay the same as they were when the page was loaded, so nothing gets updated. For reference, here is my code (obviously the alert box will eventually populate a new field). I don't want to use AJAX for this.

  $('#id_num, #id_den').on("change", function() {
     var total = $('#id_num').attr("value") / $('#id_den').attr("value");
     alert(total);     
  });

Upvotes: 1

Views: 1689

Answers (2)

vbn
vbn

Reputation: 799

attr("value") only works in jQuery versions prior to 1.9 such as 1.5.1 - 1.8.1

However, regardless of what jQuery version you're using, you should always use val()

$('#id_num, #id_den').on("change", function() {
    var total = $('#id_num').val() / $('#id_den').val();
    if(isNaN(total)){
        /* invalid inputs */
    }
    else if(!isFinite(total)){
        /* devided by 0 */
    }
    else { alert(total); }
});

You can also keyup as an alternative to change in order to make the website more responsive.

Upvotes: 1

craig.kaminsky
craig.kaminsky

Reputation: 5598

For <input> elements, the following worked for me to alert display the properly result from the division operation. .val() and not attr("value")

  $('#id_num, #id_den').on("change", function() {
    var total = $('#id_num').val() / $('#id_den').val();
    alert(total);     
  });

Upvotes: 1

Related Questions