如果选择了Option之外的任何选项,则我需要有重定向到另一个url的表单。然后显示所选的Option。
提前感谢
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<form method='post'>
<select id="selectbox">
<option value="index.html" selected>Home</option>
<option value="?hello=about" >Abut Us</option>
<option value="?hello=contact" >Contact Us</option>
<option value="?hello=blog">Blog</option>
</select>
</form>
<script>
$(function(){
// bind change event to select
$('#selectbox').bind('change', function () {
var url = $(this).val(); // get selected value
if (url) { // require a URL
window.location = url; // redirect
}
return false;
});
});
</script>
</body>
</html>
因此,假设您的URL具有诸如"?hello=about"、"?hello=xxx"等查询字符串,则以下内容应该有效。在selectbox绑定方法之后删除此代码。请记住,我还没有测试过这个代码。
var option = location.search.replace(/(^'?hello=[^&#]+).*?$/i, "$1");
$('#selectbox').val(option);
只需使用
if (url) { // require a URL
window.location.href = url; // redirect
}
因为在选项值中,您没有传递完整的URL。
试试这个:
$(function(){
// bind change event to select
$('#selectbox').bind('change', function () {
var url = $(this).val(); // get selected value
if (url) { // require a URL
$( 'form' ).attr( 'action', url ).submit();
}
return false;
});
});
我假设您希望表单做的比问题中指示的更多,否则这只是一个基本的跳转导航。如果你确实有更多的数据要传输,那么window.location不会从表单中发布这些数据。你需要做以下操作:
$(function(){
// bind change event to select
$('#selectbox').bind('change', function () {
var url = $(this).val(); // get selected value
if (url) {
// set the 'action' attribute to the
// value of the url var and submit the form.
$('form').attr('action', url).submit();
}
return false;
});
});