我有一个选择字段和一个搜索框。我希望用户选择一个食谱,然后在搜索框中按关键字搜索配料。搜索结果域应该看起来像:https://www.domain.com?s=RECIPE+KEYWORD
我下面创建的代码似乎没有附加RECIPE值,只是附加了关键字。
<select id="recipe-select" class="form-style" name="recipeType">
<option selected disabled>Select Your Recipe</option>
<option value="Cakes" name="selectedRecipe">I want to make Cakes</option>
<option value="Pies" name="selectedRecipe">I want to make Pies</option>
</select>
<div class="widget box" id="search-box">
<div class="widget-search">
<form action=" https://www.domain.com" method="post" onSubmit="search();return false;">
<input name="s" class="form-style" type="text" placeholder="Search" id="searchbox">
<button><i class="fa fa-search"></i></button>
</form>
</div>
</div>
<script type="text/javascript">
function search() {
alert("View all results?");
var a = document.getElementById("searchbox").value;
a = "https://www.domain.com/?s=<?php echo $_POST['selectedRecipe']; ?>+" + a;
a = a.replace(" ","+");
alert(a);
document.location = a;
}
</script>
我希望搜索URL的结果看起来像这样:https://www.domain.com?s=Cakes+keyword
选项值被自动附加为搜索关键字。
<?php echo $_POST['selectedRecipe']; ?>
谢谢大家的意见!解决了!:)
您应该在Javascript中获得配方类型,而不是PHP,因为PHP在提交表单之前不会运行。此外,配方选择框不在表单中,并且它没有name="selectedRecipe"
(该名称在<option>
上,但它不做任何事情)。
function search() {
alert("View all results?");
var recipeType = document.getElementById("recipe-select").value;
var keyword = document.getElementById("searchbox").value;
a = "https://www.domain.com/?s=" + encodeURIComponent(recipeType) + " " + encodeURIComponent(keyword);
a = a.replace(" ","+");
alert(a);
document.location = a;
}
试试这个。不要使用php $_POST,因为您需要发送值而不是获取值。$_POST将为空
<select id="recipe-select" class="form-style" name="recipeType">
<option selected disabled>Select Your Recipe</option>
<option value="Cakes" name="selectedRecipe">I want to make Cakes</option>
<option value="Pies" name="selectedRecipe">I want to make Pies</option>
</select>
<div class="widget box" id="search-box">
<div class="widget-search">
<form action=" https://www.domain.com" method="post" id="exampleForm" onSubmit="search();return false;">
<input name="s" class="form-style" type="text" placeholder="Search" id="searchbox">
<button><i class="fa fa-search"></i></button>
</form>
</div>
</div>
<script type="text/javascript">
document.getElementById('exampleForm').addEventListener('submit', function(evt){
evt.preventDefault();
var a = document.getElementById("searchbox").value;
a = "https://www.domain.com/?s="+encodeURIComponent(document.getElementById('recipe-select').value)+ "+" + a;
alert(a);
document.location.href = a;
});
</script>
只需在您的搜索功能中像这样添加配方和关键字…
var keyword = document.getElementById("searchbox").value;
var recipe = document.getElementById("recipe-select").value;
a = "https://www.example.com/?s=" + recipe + ' ' + keyword;
代码应该像这样…
http://codepen.io/shramee/pen/xEvrWZ
希望有帮助;)