[英]Append string to form input
I got this form: 我得到了这个表格:
<form class="navbar-form navbar-right" role="search" action="https://www.google.com/search" target="_blank">
<div class="form-group">
<input id="search" type="text" name="q" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
When a user hits the search button I want to add a string to the input. 当用户点击搜索按钮时,我想在输入中添加一个字符串。
For example, when a user types in "Foo" and submits the form, I want for the final URL to be https://www.google.com/search?q=FooSTRING
instead of https://www.google.com/search?q=Foo
. 例如,当用户输入“ Foo”并提交表单时,我希望最终URL为https://www.google.com/search?q=FooSTRING
而不是https://www.google.com/search?q=Foo
。
How would I go about achieving this? 我将如何实现这一目标?
Add an event handler to the form submit that appends the string to the input before it's POSTed. 将事件处理程序添加到表单提交中,该表单将字符串附加到输入之前。 From another StackOverflow article : 从另一篇StackOverflow文章中 :
window.onload = function() {
document.getElementById('theForm').onsubmit = function() {
var txt = document.getElementById('txtSearch');
txt.value = "updated " + txt.value;
};
};
You'd obviously have to modify the id selects to match your HTML for this to work. 很显然,您必须修改选择的id以使其与HTML匹配才能起作用。
If you want to do it in JQuery: 如果要在JQuery中执行此操作:
$('#theForm').submit(function() {
var txt = $('#txtSearch');
txt.val("updated " + txt.val());
});
You can make onclick event when pressing the button that changes input value, therefore changing final URL. 您可以在按下更改输入值的按钮(从而更改最终URL)时创建onclick事件。 Here is the code: 这是代码:
<!DOCTYPE html>
<html>
<head>
<script>
function addString()
{
var x = document.getElementById("search");
x.value = x.value + "STRING";
}
</script>
</head>
<body>
<form class="navbar-form navbar-right" role="search" action="https://www.google.com/search" target="_blank">
<div class="form-group">
<input id="search" type="text" name="q" class="form-control" placeholder="Search">
</div>
<button onclick="addString()" type="submit" class="btn btn- default">Search</button>
</form>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.