0

if I have this element in my html code

<input type="text" name="name" placeholder="city">

Why alert doesnt appear if I fill same text into this input?

  if ( $("input").val().length > 0) {
    alert("X");
  }
3
  • you have to trigger it, try keyup function Commented Nov 7, 2016 at 16:45
  • 1
    How/when are you trying to run that jQuery? Commented Nov 7, 2016 at 16:47
  • You've to watch (listen event) when the value get changed then run your code. Learn about Events in JavaScript. Commented Nov 7, 2016 at 16:50

2 Answers 2

2

This should work:

$(document).ready(function(){
       $('input[name="name"]').change(function(){
          if ( $(this).val().length > 0 ){
             //Do something
          }
       });
 });
Sign up to request clarification or add additional context in comments.

Comments

1

Try this

$('input').keyup(function(){
   if ($(this).val().length > 0){
      alert('hey');
   }
});

1 Comment

Bare in mind if you want to catch text being entered by a right click then paste or other input methods, you may need to listen for some additional events. e.g. .on("keyup change mouseup", function(){})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.