javascript获取文本框的值

时间:2012-06-07 19:40:03

标签: javascript onclick

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

<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';"

我怎么会这样做,我一直在谷歌上搜索我的小心脏。

5 个答案:

答案 0 :(得分:11)

请避免混用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()。这是working jsfiddle example

答案 1 :(得分:10)

这应该有效:

onclick="location.href='http://www.website.com/search/'+document.getElementById('search').value;"

但我不会在我的一个项目中写这个,因为直接在标签上编写脚本是一种不好的做法。

答案 2 :(得分:1)

这是a working 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 ;
});

答案 3 :(得分:0)

您可以将其添加到onclick事件中,如此

document.getEelementById("btnSearch").onclick = function(){
    location.href='http://www.website.com/search/' + document.getEelementById("search").value;
} 

编辑:aaaaand太慢了......哦。至少这不是内联的。

答案 4 :(得分:0)

你最好使用&lt;脚本&GT;此任务的标记。例如:

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

但是,您应该尝试从文本框中“清理”一些文本,以便在将其附加到网址时获得有效的网址。您应修剪文本,然后搜索特殊字符并将其转义等等。

相关问题