4

So I'm trying to have an input field where I can enter any characters, but then take the inputted value lowercase it, remove any non alphanumeric characters, leaving "." instead of spaces.

For example, If I enter:
Earth is 70% water, -!*#$^^ & 30% LAnd

The output should be:
earth.is.70.water.30.land

Any idea how this can be done without masking with jQuery?

Maverick
  • 1,123
  • 5
  • 16
  • 30

3 Answers3

12

This is not really a jQuery question, it can be done with simple Javascript. First you need to lowercase the text, then replace spaces with periods, then remove non-alphanumeric:

var myStr = "Earth is 70% water, -!*#$^^ & 30% LAnd"
myStr=myStr.toLowerCase();
myStr=myStr.replace(/ /g,".");
myStr=myStr.replace(/[^a-zA-Z0-9\.]+/g,"");

This answer would leave multiple spaces as periods, as the user inputted. If you want it to match your answer (which actually condenses multiple spaces into one), then add on an extra replace:

myStr=myStr.replace(/\.+/g, ".");
T Nguyen
  • 3,309
  • 2
  • 31
  • 48
1
$(document).ready(function () {
        $(".ui-widget-content .ui-autocomplete-input").keydown(function (event) {


            if (event.shiftKey) {
                return false;
            }
                            if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 97 && event.keyCode <= 122) || (event.keyCode >= 65 && event.keyCode <= 90)) 
                            {
                                return true;
                            }
                            else {
                                return false;
                            }
        });
    });
Marijn
  • 10,367
  • 5
  • 59
  • 80
0

Bind to the keyPress event and cancel out non alpha numeric chars.

Sample code:

$("#target").keypress(function(event) { 
    var key = event.which;
    var keychar = String.fromCharCode(key).toLowerCase();
    // allow control keys
    if ((key==null) || (key==0) || (key==8) || 
        (key==9) || (key==13) || (key==27) )
         return true;

    if ((("abcdefghijklmnopqrstuvwxyz0123456789").indexOf(keychar) == -1)) 
       event.preventDefault();   
       return false;
    }   
});
Mrchief
  • 75,126
  • 20
  • 142
  • 189
  • Is #target supposed to be the input field in this case? I'm trying to take just the value with any characters and clean it up if that makes sense – Maverick Jul 19 '11 at 03:29
  • Yes. If you're looking at just cleaning up values, then use @Nguyen's regex replace method. – Mrchief Jul 19 '11 at 03:34
  • Yup, Nguyen's regex was flawless:) With your masking method, what if the value was copy/pasted instead of typed/keypressed in? – Maverick Jul 19 '11 at 04:56
  • copy paste can be handled too by bindimg to 'paste' event. – Mrchief Jul 19 '11 at 05:06
  • The downside of cancelling out keys is that it sometimes confuses the user of your web page, who think that the input field is broken. – tgharold Mar 26 '14 at 18:52