views:

23

answers:

2

I need to make a Rails form that responds back to the user live as they input fields.

Specifically, the user will need to input four decimal fields representing data from some tests our company runs. The problem is that the testers often input incorrectly (leave out a digit, or hit a '4' instead of a '1', etc).

This is easy to check, as in real life, the inputs shouldn't vary by more than 5. I would just like to send a live message back as they input saying something like "Please double check there is no mistake in your input" if the fields vary by certain conditions.

I looked at many live validations tutorials, including the one in Advanced Rails Recipes, but a) i don't need a server request for this, and b) this is not technically a validation since I only want to warn the user of the input, not prevent them from making it.

A: 

AJAX with RJS RailsCast could help. You could write RJS that is returned once from server and then executed N times on events on the client.

Zabba
Thanks for the link
Bryan
+1  A: 

You can do this with some javascript by attaching onchange to the input fields that you want to warn users for as they're filling out the form. This way, as they move to the next field in the form, your event handler gets called, checks the value of the form field they just inputed information for, and decides whether or not to alert the user with a warning message. You wouldn't have to hit the server at all.

An example using jQuery:

$('#your_form_field').change(function () {
  var isValid = false; // Validate the input's value based on some criteria
  if (!isValid) {
    alert("Please check your work.");
  }
});
andymism
Javascript is the answer here.
Nitrodist
Thanks for the help.
Bryan
I should mention, I'm totally new to javascript (a week), so difficult for me to talk about it.
Bryan
(sorry, want to type a CR, but keep 'adding comment'). Can a JS element on one field reference the values of other fields? For example if I have 4 fields a1, a2, a3, and a4, can the onchange event then check that (say) i am within 10 units of the neighboring field?
Bryan
Yes you can. You'll want to use a JS library like jQuery that makes dealing with the DOM really easy. This way you could reference the value of field a1 and a2 (given that their id attributes are a1 and a2, respectively) using syntax like `$('#a1').val()` and `$('#a2').val()`.
andymism