Luis Valencia
Luis Valencia

Reputation: 34038

How to remove all occurence of a character when losing focus of a textbox?

I need to create in jquery a function that once a user tabs out of a control or finishes typing in the textbos, removes the # character from the field,

 $('[id$=txtClient]').keyup(function (){

}

First I dont know how to remove it, and should I do it in the keyup? or in another event?

Upvotes: 1

Views: 1480

Answers (3)

ASGM
ASGM

Reputation: 11391

I don't think the keyup is the event you want. Instead I would recommend using blur, which tracks when the element loses focus. Otherwise the user will just be unable to type #, which might be somewhat frustrating. Then you can use replace() to remove the # characters:

$('[id$=txtClient]').blur(function() {
     $(this).val( $this.val().replace(/#/g, '') );
});

The code in the function sets the element's text to be its existing text, but with each # replaced by an empty string using a regex. (Thanks to Benjamin Gruenbaum for pointing out a flaw with my first use of replace()).

Upvotes: 1

Bergi
Bergi

Reputation: 665584

You will want to use the blur event which happens when the input loses focus, and then just change the value which can be accessed as a property of the input (for a jQuery wrapper: .val()):

$("[id$=txtClient]").blur(function() {
    this.value = this.value.replace(/#/g, "");
});

Upvotes: 0

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276596

Here you go:

$('[id$=txtClient]').keyup(function (){
    var $el = $(this); // the text element
    var text = $el.val();
    text = text.split("#").join("");//remove occurances
    $el.val(text);//set it back on the element
});

Here is a working fiddle

  • .val to get the input field's value
  • .split the string on "#" and then .join it on ""
  • Place back in element
  • Happens on key up

Upvotes: 7

Related Questions