<form id="search" onSubmit="go()">
<input autofocus autocomplete="off" type="text" class="searchbar" id="searchbar" placeholder="Search Keywords: search, navigate, weather" required>
<input type="button" value="Go" class="go" id="go" onclick="go()">
</form>
我在我的网页底部有一个外部javascript文档中的函数,当我点击提交按钮时该功能正常工作,而不是当我点击输入时。
我的去功能:
function go() {
var input = document.getElementById('searchbar').value;
var words = input.split(" ");
var wordsLength = words.length;
var searchWords = '';
if(words[0] == 'search' || words[0] == 'Search') {
for(var x = 1; x < wordsLength; x++) {
searchWords += words[x];
if(x == wordsLength-1) {
} else {
searchWords += '+';
}
}
window.location.replace("http://www.google.com/#q=" + searchWords);
} else if(words[0] == 'navigate' || words[0] == 'Navigate') {
for(var x = 1; x < wordsLength; x++) {
searchWords += words[x];
if(x == wordsLength-1) {
} else {
searchWords += '+';
}
}
window.location.replace("http://www.google.com/maps/place/" + searchWords);
}
}
答案 0 :(得分:1)
您需要更改
<input type="button" value="Go" class="go" id="go" onclick="go()">
到
<input type="submit">
答案 1 :(得分:0)
<form id="search" onsubmit="go()">
<input autofocus autocomplete="off" type="text" class="searchbar" id="searchbar" placeholder="Search Keywords: search, navigate, weather" required>
<input type="submit">
</form>
答案 2 :(得分:0)
按钮的ID和功能名称相同,改变其中一个。
<form id="search" onSubmit="go()">
<input autofocus autocomplete="off" type="text" class="searchbar" id="searchbar" placeholder="Search Keywords: search, navigate, weather" required>
<input type="button" value="Go" class="go" id="_go" onclick="go()">
</form>
答案 3 :(得分:0)
尝试使用jQuery解决方案。
<form id="search">
<input autofocus autocomplete="off" type="text" class="searchbar" id="searchbar" placeholder="Search Keywords: search, navigate, weather" required>
<input type="submit" value="Submit">
</form>
在表单上提交致电go()
。
$(document).ready(function() {
$('#search').submit(function() {
//Add code from go() or just call go()
});
});
更新:
<form id="search" onSubmit="go()">
<input autofocus autocomplete="off" type="text" class="searchbar" id="searchbar" placeholder="Search Keywords: search, navigate, weather" required>
<input type="submit" value="Submit">
</form>
Jquery Part。
$(document).ready(function() {
$('#searchbar').live("keypress", function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
e.preventDefault();
e.stopPropagation();
$(this).closest('form').submit();
}
});
});
答案 4 :(得分:0)
试试这个,它正在运作。
<强> HTML 强>
<form id="search" onSubmit="return false">
<input autofocus autocomplete="off" type="text" class="searchbar" id="searchbar" placeholder="Search Keywords: search, navigate, weather" required>
<input type="button" value="Go" class="go" id="go">
</form>
<强>的JavaScript 强>
$('form').keypress(function (e) {
if (e.which == 13) {
go($('#searchbar').val());
$('form#search_form').submit();
return false;
}
});
function go(keyword){
alert('Your search keyword is [' + keyword + ']');
}
<强> Live Example 强>