JavaScript 获取文本框的值
javascript getting the value of a text box
我这里有这个文本框...
<input name="search" type="text" maxlength="512" id="search" class="searchField" autocomplete="off" title="" />
我也有这个提交
<input type="submit" name="btnSearch" value="Search" onclick="location.href='http://www.website.com/search/';" id="btnSearch" class="buttonSearch" />
我正在尝试做的是添加我文本框中的任何内容
onclick="location.href='http://www.website.com/search/';"
所以它看起来像这样..
onclick="location.href='http://www.website.com/search/what ever the user searches';"
我该怎么做,我一直在谷歌上搜索我的小心脏。
请避免混合使用 JavaScript 和 HTML。您可以删除onclick
属性,并在 DOM 加载后的某个地方用纯 JavaScript 替换它:
document.getElementById('btnSearch').onclick = function() {
var search = document.getElementById('search').value;
var searchEncoded = encodeURIComponent(search);
window.location.url = "http://www.website.com/search/" + searchEncoded;
}
还要记住有关转义搜索框的信息,例如使用 encodeURIComponent()
。这是一个工作 jsfiddle 示例。
这应该有效:
onclick="location.href='http://www.website.com/search/'+document.getElementById('search').value;"
但我永远不会在我的一个项目中写这个,因为直接在标签上编写脚本是一种不好的做法。
这是一个工作 jsfiddle
我将事件处理程序移出按钮,因为它更易于维护。 我还对搜索查询进行编码,以便它正确到达服务器。
var search = document.getElementById('search');
var submit = document.getElementById('btnSearch');
submit.addEventListener('click', function(e) {
var searchValue = encodeURIComponent(search.value); // encode the search query
window.location.href = 'http://www.website.com/search/' + searchValue ;
});
您可以像这样将其添加到 onclick 事件中
document.getEelementById("btnSearch").onclick = function(){
location.href='http://www.website.com/search/' + document.getEelementById("search").value;
}
编辑:啊,太慢了...哦,好吧。 至少这不是内联的。
最好
使用 <脚本> 标记来完成此任务。例:脚本>
<input name="search" type="text" maxlength="512" id="search" class="searchField" autocomplete="off" title="" />
...
<input type="submit" name="btnSearch" value="Search" id="btnSearch" class="buttonSearch" />
<script type="text/javascript">
var button= document.getElementById('btnSearch');
button.onclick= function(){
var text= document.getElementById('search').value;
location.href='http://www.website.com/search/'+text;
}
</script>
但是,您应该尝试从文本框中"清理"一点文本,以便将其附加到 url 时会得到一个有效的 url。您应该修剪文本,然后搜索特殊字符并对其进行转义等。
相关文章:
- 使用 jQuery 从选择标签中抓取文本
- 使用 casperjs 抓取文本节点的最快方法
- 如何分析 XML 文件和抓取文本值
- 从 URL 中抓取文本和媒体
- 突出显示:在向下钻取之前获取事件
- 使用格式化文本获取 DIV 或跨度的动态宽度高度
- 通过搜索 td 文本获取嵌套表 ID
- 将 HTML 元素的文本获取到数组中
- 如何从响应文本获取 JSON 字符串到 JavaScript 中
- 试图从X射线抓取中获取信息
- 如何根据选项文本获取选项索引
- 如何从URL中抓取文本并放置在JS数组中
- JS从文本框中抓取文本,传递给asp.net mvc ActionResult,但ActionResult参数显示为nu
- 通过其文本获取dom节点
- 如何在事件onclick中抓取文本
- 如何通过锚文本获取对象
- 在Javascript/JQuery中从超链接文本获取Href
- 在github和eclipse中,导入、推送、拉取和获取意味着什么
- 如何将函数中的文本获取到此通知警报中
- 如何从文本src抓取文本