Using jQuery to validate the sum of form fields (2)

This post is more than 2 years old.

Yesterday I blogged about how you can use jQuery to validate the sum of a set of form fields. I had some great feedback, including a comment by Gareth Arch. He raised the point that - if you had 2 form fields that need to sum to 100, why not simply just let the user edit one field and automatically set the value of the other?

I liked this idea - but I didn't want to block editing of one particular field. Depending on how you feel you may want to edit either of the two fields. I based my modification on my last demo and added the following:

function setTo100() { var theVal = parseInt($(this).val()) var otherVal = 100-theVal if( == 'phappy') $("#puhappy").val(otherVal) else $("#phappy").val(otherVal) }

$("#phappy").change(setTo100) $("#puhappy").change(setTo100)

Simply - I monitor the change event for my two form fields. When run, I get the value of the field changed and figure out what the other should be. I then look at the ID of the field changed and simply update the other one.

Simple and easy. You can demo this here.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate for HERE Technologies. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA