Posted in jQuery | Posted on 03-27-2009 | 2,663 views
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:
2 var theVal = parseInt($(this).val())
3 var otherVal = 100-theVal
4 if(this.id == 'phappy') $("#puhappy").val(otherVal)
5 else $("#phappy").val(otherVal)
6}
7
8$("#phappy").change(setTo100)
9$("#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.


Instead of using the change event, you could use the keyup event to update the values in realtime.
.change(setTo100)
to
.keyup(setTo100)
var theVal = (parseInt($(this).val()) || 0)
$("#phappy, #puhappy").keyup(setTo100)
$("input").keyup(function () {
var otherVal = 100-parseInt($(this).val())
if(this == $("input")[0]) $("input:eq(1)").val(otherVal)
else $("input:eq(0)").val(otherVal)
})
[Add Comment] [Subscribe to Comments]