-5

I have the following Javascript that checks if a field is empty.

function checkForm(form) {
    if(this.firstname.value == "") {
      alert("Please enter your First Name in the form");
      this.firstname.focus();
      return false;
    }
}

How would I rewrite this using jQuery?

michaelmcgurk
  • 5,867
  • 22
  • 75
  • 167

3 Answers3

2

You can do this with Jquery validation.

$(".form").validate({
    rules: {
        firstname: {
            required: true
        },
      },
    errorElement: 'div',
    errorPlacement: function (error, element) {
        var placement = $(element).data('error');
        if (placement) {
            $(placement).append(error);
        }
        else {
            error.insertAfter(element);
        }
    }
});

Jquery validation: https://jqueryvalidation.org/documentation/

gwesseling
  • 486
  • 5
  • 12
1

something like

var $firstName = $(this).find( "[name='firstname']" );
if ( $firstName.val().length == 0 )
{
  alert("Please enter your First Name in the form");
  $firstName.focus();
  return false;
}
gurvinder372
  • 61,170
  • 7
  • 61
  • 75
1

It's pretty simple . Details commented in Snippet

SNIPPET

/* When any input has lost focus (ie blur)
|| and it's value is false, raise the alarm
*/
$('input').on('blur', function() {
  if (!$(this).val()) {
    alert('PUT SOMETHING IN THIS BOX');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<input>
zer00ne
  • 31,838
  • 5
  • 32
  • 53