File Under: JavaScript

Sanitize Text with MooTools

The code, and the template, are referred to in Webmonkey’s Get Started With MooTools reference page. In this example, the HTML page contains several forms. Using JavaScript and the MooTools web framework, we will pull out the last letter of a typed form, clean up unused space in another form and automatically format a telephone number.

The Code

<html>



<head>

<title></title>

<script src="mootools.js"></script>

	<style>

	</style>

	<script>

	window.addEvent('domready', function () {

		$("myinput").addEvent('keyup', function(event) {

			$("myoutput").value = event.key;

		});



		String.implement({

			cleancaps: function(){

				var mystr = this;

				mystr=mystr.clean();

				mystr=mystr.capitalize();

				return mystr;

			}

		});





		String.implement({

			format_phone: function() {

				var newphone = this.replace(/[^d]/g, "");

				var phonematches = newphone.match(/^(d{0,3})(d{0,3})(d{0,4})/);

				if (phonematches[1].length > 0)

				{

					newphone = "(" + phonematches[1];

				}

				if (phonematches[1].length == 3)

				{

				  newphone += ") " + phonematches[2];

				  if (phonematches[2].length == 3)

				  {

				    newphone += "-" + phonematches[3];

				  }

				}

	  			return newphone;

			}



		});



		// Uncomment next line (and comment the one following it) to only format the first phone number box

		//$("phonenumber").addEvent('keyup', function (event) {

		$$(".phone").addEvent('keyup', function (event) {

			var txtbox = event.target;

			if (event.key != 'delete' && event.key != 'backspace')

			{

				txtbox.value = txtbox.value.format_phone();

			}



		});



	});



	</script>



</head>

<body>



<p>

Type in here: <input type="text" id="myinput" />

<br />

Latest key will show up here: <input type="text" id="myoutput" />

</p>



<p>

Type some text: <input type="text" id="myhead" value="    Monkeys      rule!    " /><input type="button" value="Cleancaps it!" onclick="$('myhead').value=$('myhead').value.cleancaps()" />

</p>





<p>

Phone number: <input type="text" id="phonenumber" class="phone" />

<br />Phone number: <input type="text" id="phonenumber2" class="phone" />



</p>



</body>

</html>

What it Looks Like