Sunday, November 28, 2010

Clean URL Form Submission using JQuery – A Quick Tip

Its very straight forward, and I hope it does not require any description.
<script>
   $(function(){
 $("form#tweak_search").submit(function(){
    $search_key = $(this).children("input[type=text]").val();
    $new_action_path = "http://new_search_action/"+$search_key;
    location.href = $new_action_path;
    return false;
 });
   });
</script>
<form method="get" id="tweak_search" action="old_search_action_goes_here">
   <input type="text" name="search">
   <input type="submit">
</form>
 
Variations
  • If .children() function does not work, you might use .find() – the difference is that children() fetches only a single matching object, whereas find() searches any number of children available.
  • You may provide  id or name in the text input field selector if there are more than one text fields.
    eg, $(this).children(“input#search-key”).val();
    eg, $(this).children(“input[name=query]“).val(); .. etc

No comments:

Post a Comment