I'm trying to do some simple form validation, and I can get one response to work but not another one. I have a simple form in a sidebar block (in Drupal) that is an area calculator (user enters length, width, and height, clicks Calculate button, and area field is filled in via jQuery). That part works fine. I'm trying to add some form validation so that the user is only allowed to enter numbers in the fields using the isNaN function, and the part where I (try to) display a message isn't. If I use this:
$(function() { $('#calculate-square-form input:text').blur(function() { if (isNaN($(this).val())) { alert("Only numbers are allowed"); $(this).val(''); }; }); }); it works fine; the alert box is displayed, and the field is blanked out. However, if I try to be a little more graceful and display the error as HTML like this: $(function() { $('#calculate-square-form input:text').blur(function() { if (isNaN($(this).val())) { var errorMessage = 'Please enter only numbers'; $('<div></div>').text(errorMessage).appendTo('#edit-square- area'); $(this).val(''); }; }); }); then nothing happens (I plagiarized this from chapter 8 of "Learning jQuery"). I tried this: $(function() { $('#calculate-square-form input:text').blur(function() { if (isNaN($(this).val())) { var errorMessage = "Please enter only numbers"; $('<div></ div>').addClass('error').text(errorMessage).insertAfter('#edit-square- area'); $(this).val(''); }; }); }); but no luck. This will work $(function() { $('#calculate-square-form input:text').blur(function() { if (isNaN($(this).val())) { var errorMessage = "Please enter only numbers"; $('#edit-square-area').after('<div>'+errorMessage+'</div>'); */ $(this).val(''); }; }); }); but it will display the error message for each time the user exits the field. I want to add a class to the new div so I can filter on it and delete it if it exists at the beginning of the function, but adding .addClass adds the class to #edit-square-area, not my new div. How can I add the class to my new div? Thanks.