简体   繁体   中英

After regular expression overwrite text in a html input field

I have several input fields that I need to filter the input on. I've put them in a class and used a regular expression to limit the characters to numbers, letters, and underscore. That works fine, but when I tab from one input field to the next, the cursor moves to the end of the input text. I want it to be highlighted so that it can be typed over if desired instead of having to highlighting it with the mouse first.

<input type="input" class="jqfc" value="one"><br>
<input type="input" class="jqfc" value="two"><br>    
<input type="input" class="jqfc" value="three"><br>    
<input type="input" value="highlights"><br>    


jQuery('.jqfc').keyup(function () {
      this.value = this.value.replace(/[^a-z0-9\_]/gi, "");
});

sample: http://jsfiddle.net/ngwr6/2/

jQuery('.jqfc').keyup(function (e) {
  if (e.keyCode !== 9){
    this.value = this.value.replace(/[^a-z0-9\_]/gi, "");
  }
});

This way it wont run the logic if the tab key is pressed. I thought of doing something like select() , but then that happens every time you type.

This ought to do the trick:

jQuery('.jqfc').keyup(function () {
    var regex = /[^a-z0-9\_]/gi;
    if(this.value.match(regex)){
        this.value = this.value.replace(regex, "");
    }

});

jQuery('.jqfc').on('focus, click', function(){
        this.select();
});

http://jsfiddle.net/ngwr6/5/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM