Using jQuery to Make a Smart Search
Recently I've been forced to develop a relationship with jQuery (something I had no interest in while I was working with team awesome). I have to admit it has been quite pleasant and my tolerance has grown into a very strong liking of the library (so I'm a little slow). This proved very useful when I was asked to make a search field do more than just search for an ID. I decided NOT to fowl up our nice sleek looking header with a clunky drop down box, instead I turned to jQuery to make the search bar intuitive...observe.
$("#searchForm").submit(function() { //the regular expressions in this function are not meant for validation as much as determining which value to search by. var submitted_appid = $(".search input[name=AppID]").val(); if(/^[\d]+$/.test(submitted_appid) == true) { //do nothing since the input is already properly named } else if(/^[\d-]+$/.test(submitted_appid) == true) { //change name of input to SSN $(".search input[name=AppID]").attr("name","SSN"); } else if(/^[A-Za-z]+$/.test(submitted_appid) == true) { //change name of input to LastName $(".search input[name=AppID]").attr("name","LastName"); } else { //no match, alert the rep and return false alert("invalid search value:\nfor SSN please use numbers and at least one dash '-'\n for LastName use only letters\n for AppID use only numbers") return false; } //there was a match add an action and submit the form. $(this).attr("action",'search.php'); $(this).submit(); }); |
The HTML
<div class="search">
<form id="searchForm" name="searchForm" method="post" action="">
<input type="text" name="AppID" value="Search..." />
</form>
</div> |
Then your search app would do something like the following
if(isset($_POST['AppID']) { //enter sql code here } else if(isset($_POST['SSN']) { //enter sql code here } else if(isset($_POST['LastName']) { //enter sql code here } |
Basically the jQuery decides what to search on based on the characters in the input field, if the wrong mix of characters is present then we fire off an alert message notifying the irresponsible party and correcting their ignorant ways.
Print This Post