1

I am using the following jquery snippet to append ' UK' to a text input when the user presses enter on his/her keyboard:

jQuery('#myinput').one('keypress', function (e) {
  if (e.which == 13) {
    jQuery('#myinput').val($('#myinput').val() + ' UK');
    return false;
  }
});

However, I only want 'UK' to be appended if the text doesn't already contain 'UK'. Is there any easy way to check if 'UK' is already present using jQuery?

I have tried the following, but this appends nothing either way:

if ( !'#myinput:contains("UK")') {
   jQuery('#myinput').one('keypress', function (e) {
      if (e.which == 13) {
         jQuery('#myinput').val($('#myinput').val() + ' UK');
         return false;
      }
   }
});

1 Answer 1

4

Try .indexOf()

if (e.which == 13 && this.value.indexOf('UK') === -1){


this keyword


if (e.which == 13 && this.value.indexOf('UK') === -1) {
    this.value = this.value + 'UK';
}
Sign up to request clarification or add additional context in comments.

5 Comments

Great, thanks. This works very nicely! Can I also check if it is lowercase 'uk' somehow as well?
@user1444027 Yes if (e.which == 13 && (this.value.indexOf('UK') === -1 || this.value.indexOf('Uk'))) {
this.value.toLowerCase().indexOf('uk')
@user1444027 or better just check if (e.which == 13 && this.value.toUpperCase().indexOf('UK') === -1)
@BlackSheep thanks i was on it too u beat my fingers :)

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.