Reputation:
I need to have the form to redirect to another url if any of the options are selected apart from Option Then show selected Option.
Thank you in advance
<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>
Upvotes: 0
Views: 831
Reputation: 8181
So, assuming your URLs have query strings such as "?hello=about", "?hello=xxx" etc. the following should work. Drop this code just after the selectbox bind method. Bear in mind that I've not tested this code.
var option = location.search.replace(/(^\?hello=[^&#]+).*?$/i, "$1");
$('#selectbox').val(option);
Upvotes: 1
Reputation: 1964
I'm assuming you want the form to do more than what is indicated in your question, otherwise this is just a basic jump navigation. If you DO have more data to transmit then window.location won't post that data from the form. You need to do the following:
$(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;
});
});
Upvotes: 0
Reputation: 897
Try this:
$(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;
});
});
Upvotes: 0
Reputation: 4645
Just Use
if (url) { // require a URL
window.location.href = url; // redirect
}
Because in the options value you're not passing the complete URL.
Upvotes: 1