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(this.id == '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.
Archived Comments
In your demo code you have a comma after max:100 in the validate rules, and this made it generate an error in IE but not Firefox. After taking that out it works fine.
Oops. Sorry. Fixed and pushed up.
@Raymond:
Instead of using the change event, you could use the keyup event to update the values in realtime.
Nice. That does work better. For folks who visit the demo, please be sure to view source, although the only change was from
.change(setTo100)
to
.keyup(setTo100)
Works great, but if you enter a value that can't be parsed as an integer, it throws "NaN" in the other form field. You can get around this by using:
var theVal = (parseInt($(this).val()) || 0)
Never mind the last post, not sure what was happening. It appears jQuery wasn't validating properly, but it's working now.
One other code shortcut you can use is:
$("#phappy, #puhappy").keyup(setTo100)
You can even do it based on class or any other selectors, so you don't even need ids.
$("input").keyup(function () {
var otherVal = 100-parseInt($(this).val())
if(this == $("input")[0]) $("input:eq(1)").val(otherVal)
else $("input:eq(0)").val(otherVal)
})
is it possible to do a @keyup after the 2nd character?
No. Event handles are based on events, not values. But obviously your code could look at the val, and if the size is 1, do nothing.
ok you can obviously tell i'm a newbie to custom javascript :) thanks. just fyi, i was trying to bind a form to a cfdiv using zipcode to find results, but i didnt want the bind to kick off until the zipcode field length was 5 :) hence my question. so i'll change it from a bind url to a bind javascript and count the size before initiating the bind in the cfdiv??? i'll see if that works.
Sure, or your server side code could also check the length. It is better, traffic wise, to never send the request if it is too short.