获取选项值并附加到搜索作为附加关键字?

时间:2016-11-01 09:34:38

标签: javascript php jquery html wordpress

我有选择字段和搜索框。我希望用户选择食谱,然后在搜索框中按关键字搜索成分。搜索结果域应如下所示: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>

我希望搜索网址的结果如下所示:https://www.domain.com?s=Cakes+keyword

选项值自动附加为搜索关键字。以下似乎不起作用。

<?php echo $_POST['selectedRecipe']; ?>

感谢大家的投入!解决! :)

3 个答案:

答案 0 :(得分:1)

您应该在Javascript中获取配方类型,而不是PHP,因为PHP在您提交表单之前不会运行。此外,配方选择框不在表单中,并且没有while(1)(该名称在name="selectedRecipe"上,但是没有做任何事情。)

<option>

答案 1 :(得分:1)

试试这个。不要使用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>

答案 2 :(得分:0)

只需在搜索功能中添加这样的食谱和关键字......

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

希望有所帮助;)