我有一个简单的两个下拉表单,需要根据下拉列表中的给定值重定向。
jQuery(document).ready(function(){
var location = jQuery('#Location option:selected').val();
var style = jQuery('#Style option:selected').val();
jQuery('#DropSearch').click(function (e){
e.preventDefault();
e.stopPropagation();
window.location.href = 'http://showroomworldwide.com/?geodir_search=1&stype=gd_place&s=' + location + '&stype=gd_place&s=' + style;
});
});
<form id="CustomSearch">
<select id="Location">
<option value='northeast'>North East</option>
<option value='west'>West</option>
<option value='midwest'>Mid West</option>
<option value='south'>South</option>
</select>
<select id="Style">
<option value='industrial'>Industrial</option>
<option value='farmhouse'>Farmhouse</option>
<option value='contemporary'>Contemporary</option>
<option value='beach+style'>Beach Style</option>
<option value='traditional'>Tradtional</option>
</select>
<button id="DropSearch">
<i class="fa fa-search" aria-hidden="true"></i></button>
</form>
由于某种原因,重定向只会选择下拉列表的第一个选项(或浏览器窗口加载时选择的选项)......任何想法为什么会发生这种情况? http://showroomworldwide.com/您可以访问工作示例的网址。
答案 0 :(得分:1)
您不需要测试所选的选项。只需获取选择的值。 val()
方法将返回字段的当前值,该值将是所选的任何值。
但是,您必须在点击按钮时获取这些值,而不是之前。
此外,由于您没有使用提交按钮,因此没有需要取消的原生行为,因此您可以删除e.preventDefault()
和e.stopPropagation()
。
$(function(){
$('#DropSearch').click(function (e){
// Now that the button has been clicked, just get the
// value of the elements. No need to get the selected option
var location = jQuery('#Location').val();
var style = jQuery('#Style').val();
// Test to see if the right choices were stored:
console.log(location, style);
window.location.href =
'http://showroomworldwide.com/?geodir_search=1&stype=gd_place&s=' +
location + '&stype=gd_place&s=' + style;
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="CustomSearch">
<select id="Location">
<option value='northeast'>North East</option>
<option value='west'>West</option>
<option value='midwest'>Mid West</option>
<option value='south'>South</option>
</select>
<select id="Style">
<option value='industrial'>Industrial</option>
<option value='farmhouse'>Farmhouse</option>
<option value='contemporary'>Contemporary</option>
<option value='beach+style'>Beach Style</option>
<option value='traditional'>Tradtional</option>
</select>
<button id="DropSearch">
<i class="fa fa-search" aria-hidden="true"></i></button>
</form>
&#13;
答案 1 :(得分:1)
var location = jQuery('#Location option:selected').val();
var style = jQuery('#Style option:selected').val();
您准备好在文档开始时立即执行这些行。因此,它们的价值将是页面加载时的任何值。它们不会在点击逻辑上重新评估。如果要在单击时拾取值,请将它们移动到您的单击逻辑中。