I have a list of pages generated by Wordpress within a drop down, on click, how can submit the form and goto the page that was selected?
<form id="work" action="" method="post">
<select name="work">
<?php $pages = get_pages(array('child_of' => '15', 'sort_column' => 'menu_order'));
foreach($pages as $post) {
setup_postdata($post);
$fields = get_fields(); ?>
<option class="work-dropdown" value="<?php echo the_permalink(); ?>"><?php echo the_title(); ?></option>
<?php } wp_reset_query(); ?>
</select>
</form>
I tried this jquery but I'm not sure if that's correct and what to put in the action:
<script type="text/javascript">
jQuery(document).ready(function( $ ) {
$('.work-dropdown').change(function() {
$('#work').submit();
});
});
</script>
If you simply want to redirect the page try:
<script type="text/javascript">
jQuery(document).ready(function( $ ) {
$('select[name="work"]').change(function(){
window.location = $(this).val();
})
});
</script>
You may want to add an ID to the select to make the jQuery selector faster.
So you would add: id="page-redirect"
to the select change the jQuery object to $('#page-redirect')
. ID's are selected much faster than classes or attributes.
If you want the form to post to the selected URL then try:
<script type="text/javascript">
jQuery(document).ready(function( $ ) {
$('#work select[name="work"]').change(function(){
$('#work').attr('action', $(this).val()).submit();
});
});
</script>
The .change()
cannot be written on option
's selector as you've written. It needs to be the select
. So, $('[name=work]')
needs to be your selector.
Also, it looks like your link is present in the value of the option. The below code should work.
$('[name=work]').change(function() {
window.location = $(this).val();
});
EDIT:
You cannot do submit & then redirect to the page if you're resetting the dropdown on submit. In case, you need to submit and you didn't reset the dropdown & then redirect based on the URL or index,
$('[name=work]').change(function() {
$('#work').submit();
});
//handle it on document ready & assuming your index's first option is plain text 'Select from below'
if($('[name=menu] :selected').index() > 0)
{
window.location = $(this).val();
}
jQuery(document).ready(function ($) {
$('.work-dropdown').change(function () {
$('#work').attr('action', $(this).val());
$('#work').submit();
});
});
Will do this