0

I am pretty new to jQuery so I have a problem with this. I am trying to check if input is empty by jQuery. I have this script:

$('#submit').click(function(){
  if($.trim($('#username').val()) == ''){
    alert('Input can not be left blank');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="username" id="username" type="text" placeholder="Enter your Username"/>
<button class="btn btn-info btn-block login" name="submit" id="submit" type="submit">Create an Account</button>

Thanks for reply.

Jed Fox
  • 2,979
  • 5
  • 28
  • 38
Adam Šulc
  • 55
  • 1
  • 8

1 Answers1

1

Check the length property to determine if it's empty:

if ($.trim($('#username').val()).length > 0) {
// not empty
}

Edit: Removed white spaces $.trim

Tony M
  • 741
  • 4
  • 16
  • 2
    This doesn't account for whitespace only input, like the OP is removing with the trim. Edit: and you have an unclosed '(' in your code. – Taplar Nov 06 '17 at 17:13