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.

10
  • 1
    You didn't state what your problem is. Commented Nov 6, 2017 at 17:08
  • 2
    What's your actual question? "How should I best check if a string is empty in Javascript"? stackoverflow.com/questions/154059/… Commented Nov 6, 2017 at 17:08
  • It seems that your code is working. What is the problem? Commented Nov 6, 2017 at 17:10
  • My problem is that if I click the button the alert doesnt show up. Commented Nov 6, 2017 at 17:14
  • I see the alert if I run the code in this post. Commented Nov 6, 2017 at 17:14

1 Answer 1

1

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

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

Edit: Removed white spaces $.trim

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.