user853575
user853575

Reputation: 121

Jquery form validation

I am just trying to print a error message if someone leaves the text field blank using jquery.But it is not being displayed. This is html code:

 <form id="form1" runat="server">
    <div>
    <table>
     <tr>
    <td>
   <label>Name</label></td>
   <td> <input class="required" type="text" name="name" id="name" /><span>(required)</span></td>
     </tr><tr>
    <td><br/><label>Address</label></td>
    <td><input class="required" type="text" name="address" id="address"/><span>(required)</span></td></tr>
     </table>
    </div>
    </form>

This is Jquery code.

$(document).ready(function () {
   var requiredFlag = ' * ';
    $('form :input').filter('.required').next('span').text(requiredFlag).end();
    if ($(this).is('.required')) {
       if (this.value == '') {
       var errorMessage = 'This is a required field';
                             };
            $('span></span').text(errorMessage).appendTo($(this));
                             }; 
});

May be i am missing something. Help experts. Thank you.

Upvotes: 1

Views: 1774

Answers (2)

Ram
Ram

Reputation: 144729

  1. this in your code refers to window/document object not the input elements;
  2. There are some typos in your code => $('span></span');
  3. There is no event handler in your code for validating the inputs
  4. You have span elements in your markup and there is no need for generating a new one
  5. You can use the form submit event for validating the inputs
  6. The :input selector has been deprecated

Try this:

var errorMessage = 'This is a required field';
$('form input.required').next().text('*');

$('form').submit(function(){
   var errors = 0;
   $('input.required', this).each(function(){
       if (this.value == '') {
          $(this).next().text(errorMessage);
          errors++;
       }
   })
   if (errors > 0) {
     return false // prevents the default action of the event if there are errors
   }
})
  1. submit()
  2. next()
  3. each()

Upvotes: 1

speti43
speti43

Reputation: 3046

I don't think it's a good selector: $('span></span'). Use jquery Siblings selector, and change the span text with .text() or .html() function http://api.jquery.com/html/

Upvotes: 0

Related Questions