Skip to content
Advertisement

Appending form input value to action url as path

I have a form like this:

<form action="http://localhost/test">
    <input type="text" name="keywords">
    <input type="submit" value="Search">
</form>

If I type a value, let’s say: ‘hello’ in the text input field and submit the form, the URL looks like: http://localhost/test/?keywords=hello.

I want the value to get appended to the action path. So basically, after the form submission the URL should look like:

http://localhost/test/hello

Advertisement

Answer

You can use onsubmit attribute and set the action inside a function for example:

<form id="your_form" onsubmit="yourFunction()">
    <input type="text" name="keywords">
    <input type="submit" value="Search">
</form>

function yourFunction(){
    var action_src = "http://localhost/test/" + document.getElementsByName("keywords")[0].value;
    var your_form = document.getElementById('your_form');
    your_form.action = action_src ;
}
    
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement