Appending form input value to action url as path

此生再无相见时 提交于 2019-12-17 19:45:55

问题


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

回答1:


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 ;
}



回答2:


You can use onsubmit and use jQuery to obtain the same result.

Check the following.

HTML Code:

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

jQuery Code:

    function yourFunction(){

    var action_src = $("keywords").val();
    var your_form = $('your_form').val();

    var urlLink = "http://localhost/test/";
    urlLink = urlLink + action_src;



    your_form.action = urlLink;

}


来源:https://stackoverflow.com/questions/34128361/appending-form-input-value-to-action-url-as-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!