Sunday, January 29, 2012

jQuery Autocomplete via TextArea

It is always desirable to prevent users from making typos.  One tool that is great at preventing this is the jQuery AutoComplete.  However, sometimes you want to drive it off of client entered data and not via a constant array or ajax call.  Let's look at an example where we populate the AutoComplete via an existing TextArea on the page.

The jQuery splits on newline and fills the autocomplete whenever the textarea changes:
$("#Choices").change(function () {    
    var choices = $(this).val().split('\n');    
    $("#DefaultChoice").autocomplete({        
        source: choices    
    });
});
And the supporting markup:
<div id="DivList" class="dataChoice">
    <label for="Choices">Choices:</label>
    <textarea cols="20" id="Choices" name="Choices" rows="2"></textarea>
    
    <label for="DefaultChoice">Default Choice:</label>
    <input id="DefaultChoice" name="DefaultChoice" type="text" value="" />
</div>
Get the full source on GitHub.

No comments:

Post a Comment

TaskForce!

Coming soon, a new kind of todo app. A gamified task manager. Get rewarded for completing tasks with gold. Use your bank to upgrade your shi...