javascript 将表单输入值作为路径附加到操作 url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34128361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:16:48  来源:igfitidea点击:

Appending form input value to action url as path

javascripthtmlformsurl-routing

提问by littleibex

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.

如果我输入一个值,比方说:在文本输入字段中输入 'hello' 并提交表单,则 URL 如下所示: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:

我希望将值附加到操作路径。所以基本上,在提交表单后,URL 应该如下所示:

http://localhost/test/hello

采纳答案by prieston

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

您可以使用onsubmit属性并在函数内设置操作,例如:

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

回答by Dulith De Costa

You can use onsubmitand use jQueryto obtain the same result.

您可以使用onsubmitjQuery来获得相同的结果。

Check the following.

检查以下内容。

HTML Code:

HTML代码:

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

jQuery Code:

jQuery 代码:

    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;

}