JavaScript 获取文本框的值

javascript getting the value of a text box

本文关键字:取文本 获取 JavaScript      更新时间:2023-09-26

我这里有这个文本框...

<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。您应该修剪文本,然后搜索特殊字符并对其进行转义等。