14

I have input-box. I'm looking for a way to fire-up alert() if first character of given string is equal to '/'...

var scream = $( '#screameria input' ).val();

if ( scream.charAt( 0 ) == '/' ) {

  alert( 'Boom!' );

}

It's my code at the moment. It doesn't work and I think that it's because that browser doesn't know when to check that string... I need that alert whenever user inputs '/' as first character.

0

2 Answers 2

26

Try this out:

$( '#screameria input' ).keyup(function(){ //when a user types in input box
    var scream = this.value;
    if ( scream.charAt( 0 ) == '/' ) {

      alert( 'Boom!' );

    }
})

Fiddle: http://jsfiddle.net/maniator/FewgY/

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

8 Comments

There are one unexpected bug. When alert() is fired-up, user will try to close it with "Enter", but that will call alert() again. How would you solve this?
well what you can do is clear out the value before the Boom so they submit nothing: this.value = ''
@daGrevis -- #1 use jsFiddle. #2, the isFired variable is not in the global scope
@Neal But I use it only in that anonymous function... so does it matters? P.S. I will use jsFiddle. ;)
yes it only exists in that anon. and never at any other point. it disappears. -- poof --
|
4

You need to add a keypress (or similar) handler to tell the browser to run your function whenever a key is pressed on that input field:

var input = $('#screameria input');
input.keypress(function() {
  var val = this.value;
  if (val && val.charAt(0) == '/') {
    alert('Boom!');
  }
});

2 Comments

Do not use input.val(), use either $(this).val() or this.value, you have no idea how many inputs there are.
@Neal, ha, true. I guess that's a sign that we're doing it right =)

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.