April 8, 2012

html form button link to url

Question by Ferguzz

I have a simple search form with a box and a button.

<form action = "/search/" method = "get">
<input id = "search_box" type ="text" name = "location" value placeholder = "Where are you?" />
<input id = "search_button" type="submit" value = 'Go' />
</form>

This sends me to /search/?location=whatever

How do I get this to send me to /search/whatever instead? – i.e. no GET data, just an URL.

Answer by Starx

You cannot rewrite the form post methods like that. A way to do this efficiently is through a .htaccess at the root.

RewriteEngine On
RewriteRule ^search/?location=(.*)$ search/$1

This changes /search/?location=whatever to /search/whatever

Or, If you are looking for a complicated JS solution. Here is one using jQuery

$("form").submit(function() {
    var search = $("#search_box").val(); //get the element
    $(this).attr("action", $(this).attr("action")+search);  //attach to the post url
    $("#search_id").remove();  //remove the element, so it doesnot get sent
    console.log($(this).attr('action')); //check the console, if the action was changed and yes it was
    //return false; //continues the post to the new url if commented
});

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!