我有一个带文本框和3个单选按钮的搜索按钮。我想要做的是在用户单击搜索按钮后将所选单选按钮的值传递到URL。现在,url中显示的唯一内容是用户在文本框中输入的内容。因此,如果用户选中游戏单选按钮然后点击搜索,则在网址中会显示类似m =游戏...
HTML:
<input type="text" name="search-bar" id="search-bar" class="search-box" onkeypress="return submitEnter();"/>
<button onclick="redirect();" class="search-button">Search</button><br/>
<input type="radio" name="selection" value="Music" id="music-button" class="radio-button"><span class="radio-text">Music</span>
<input type="radio" name="selection" value="Books" id="books-button" class="radio-button"><span class="radio-text">Books</span>
<input type="radio" name="selection" value="Games" id="games-button" class="radio-button" ><span class="radio-text">Games</span>
JS:
function redirect()
{
var url = "mylink.com";
url = url+"&q="+document.getElementById("search-bar").value;
location.href=url;
}
function submitEnter()
{
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (e)
keycode = e.which;
else
return true;
if (keycode == 13)
{
redirect();
return false;
}
else
return true;
}
答案 0 :(得分:0)
除非我误解了某些内容,否则您只需提交表格即可。将其包裹在form
元素中,然后将button
更改为type="submit"
。
然后你可以抛弃js重定向并使submitEnter函数更干。
function submitEnter(form) {
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (e)
keycode = e.which;
else
return true;
if (keycode == 13) {
form.submit();
return false;
} else
return true;
}
<form method="get" action="http://www.example.com">
<input type="text" name="search-bar" id="search-bar" class="search-box" onkeypress="return submitEnter(this);"/>
<button type="submit" class="search-button">Search</button>
<br/>
<input type="radio" name="selection" value="Music" id="music-button" class="radio-button"><span class="radio-text">Music</span>
<input type="radio" name="selection" value="Books" id="books-button" class="radio-button"><span class="radio-text">Books</span>
<input type="radio" name="selection" value="Games" id="games-button" class="radio-button"><span class="radio-text">Games</span>
</form>