【问题标题】:Form action change based on option select works only when in home基于选项选择的表单操作更改仅在在家时有效
【发布时间】:2020-07-30 08:02:20
【问题描述】:

我正在为我正在处理的 WordPress 项目创建自定义搜索表单。 searchform.php 代码如下所示:

<form role="search" method="get" id="searchform" class="searchform col-md-4" >
    <input type="search" value="<?php echo get_search_query(); ?>" name="term" id="s" class="form-control" placeholder="Find Freelancers & Agencies">
    <select id="search-options">
        <option>Select...</option>
        <option value="Projects">Projects</option>
        <option value="Freelancers">Freelancers</option>
    </select>
</form>

基本上,我想根据用户选择的选项来更改表单的操作。为此,我正在使用以下脚本:

jQuery(document).ready(function(){

jQuery("#search-options").change(function(){
 // change fn on dept id
 var selected_opt = $(this).children(":selected").text(); // Get the selected option value

 switch(selected_opt){
 case "Projects":
    jQuery("#searchform").attr('action', '/advanced-search/');
 break;

 case "Freelancers":
    jQuery("#searchform").attr('action', '/service-provider-search/');
 break;

 default:
    jQuery("#searchform").attr('action', '#');
 // Default action
 }
});
});

脚本在我的 functions.php 文件中正确排队。

我注意到虽然当我在主页上时它工作正常,但当我在其他页面上时它不起作用。当我在其他页面使用搜索表单时,结果 URL 为http://example.com/page/?term=search_term

有什么建议吗?

【问题讨论】:

  • 验证这些页面中是否存在&lt;form&gt;,以及脚本是否也在这些页面中加载。只需在 jQuery(document).ready 中添加一个 console.log('Form script loaded.'); 并查看它是否出现在浏览器的 DevTools 控制台中(Chrome 中的 F12)。
  • 嗨@AugustoMoura。感谢你的回复。是的,我可以确认表单和脚本都已加载到其他页面上。

标签: php jquery wordpress search


【解决方案1】:

对于任何想知道的人,这是第 3 行中的一个错字。由于已知的兼容模式限制,在使用 jQuery 在 WordPress 中开发时,所有“$”符号都应该是“jQuery”。

这一行:

 var selected_opt = $(this).children(":selected").text(); // Get the selected option value

应该是这样的:

 var selected_opt = jQuery(this).children(":selected").text(); // Get the selected option value

【讨论】:

    猜你喜欢
    • 2014-11-15
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    相关资源
    最近更新 更多