by aherrick
22. January 2010 04:13
Working on an application I needed to write a script to only allow Alphanumeric characters (Letters and Numbers only) for dynamic XML generation. We wanted the solution to be smart enough that when the user is typing in a textbox, any character other than Alphanumeric is automatically removed while they are typing into the input. Using a combination of jQuery and regular Javascript the solution becomes simple.
Take a look at the Javascript used below.
<script type="text/javascript">
$(function() {
$('#basicInput').keyup(function() {
// cache input and value
var input = $('#basicInput');
var value = $('#value');
// only allow letters, numbers, don't allow spaces
var tempVal = input.val().match(/[A-Za-z0-9]+/g);
tempVal = tempVal == null ? "" : tempVal.join("");
// display formatted input
input.val(tempVal);
value.html(tempVal);
});
});
</script>
First we attach a jQuery keyup event to the text input. We then get the value of the input and run it through a basic regular expression to get the match. We then update the input with the array of matched values.
Great! Check out the example page to see it in action!
cb83006a-0315-4b56-8599-11451b4b79f0|0|.0
Tags: