Auto-Capitalize using JavaScript

I help in running and continuously improving a classifieds website. Now, the problem is that for sites that are that public and with a generally public audience, you get all kinds of inputs, legitimate and otherwise. Every so often, to make things work and look like they should, some idiot-proofing is required. So, find below a script you can use to auto-capitalize input like I had to for my listing titles across the sites I am involved in.

Lets assume a simple form like the one below…

<form>
Name: <input type=”text” name=”name”><br/>
Email: <input type=”text” name=”email”><br/>
</form>

 

Now, to whip up some simple JQuery to auto capitalize any text input into the above form

<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js”></script>
<script>
$(document).ready(function() {
$(“input”).keyup(function() {
var val = $(this).val()
$(this).val(val.toUpperCase())
})
})
</script>

 

This code binds to all input fields on the page. You can filter it to a particular field_id, form_id, or other DOM attribute, but this works fine. The code listens for the keyup event and simply takes the entire val and converts it to upper case.

Happy idiot proofing!

Share

Leave a Reply