How to dynamically calculate a form field 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");

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();
        /* 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.