-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
  • 6,367
  • 23
  • 94
  • 190

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
  • 483
  • 6
  • 13
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
  • 66,980
  • 10
  • 72
  • 94
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
  • 41,936
  • 6
  • 41
  • 68