How to replace a javascript select box onchange event to a form submit action?

I have a small problem that probably has a very simple fix. I have been using the wp_get_archives() function to produce a dropdown select form. See the full code below:

<form id="side-arch">
     <select name="archive-dropdown" onchange="document.location.href=this.options[this.selectedIndex].value;">
          <option value=""><?php echo esc_attr( __( 'Select Month' ) ); ?></option> 
          <?php wp_get_archives( array( 'type' => 'monthly', 'format' => 'option', 'show_post_count' => 1 ) ); ?>
     </select>
     <input type="submit" value="Go" id="submit" />
</form>

I would like to make this use the submit button, instead of the onchange event to execute the action. Obviously, what I should do is remove the onchange element and add a form action. I have tried formatting it just like my functional category dropdown, which would achieve it by doing this:

<form id="side-arch" action="<?php echo esc_url( home_url( '/' ) ); ?>" method="get">
     <select name="archive-dropdown">
          <option value=""><?php echo esc_attr( __( 'Select Month' ) ); ?></option>
          <?php wp_get_archives( array( 'type' => 'monthly', 'format' => 'option', 'show_post_count' => 1 ) ); ?>
     </select>
     <input type="submit" value="Go" id="submit" />
</form>

However, this does not work. I am guessing that there is something wrong with the url in the form action, as it just sends me to the home page of the site.

Anyone have any ideas on how to switch this over to using a Go button?

Solutions Collecting From Web of "How to replace a javascript select box onchange event to a form submit action?"

It’s not working because:

  • You are redirecting home
  • You don’t listen for the $_GET variable so the archive link is just appended to your home url

You need to add a function that listens for that $_GET variable.

just add this to your functions.php file

add_action( 'template_redirect', 'wpse_archive_select' );
function wpse_archive_select(){

  if( isset( $_GET[ 'archive-dropdown' ] ) ){
    die( wp_safe_redirect( $_GET[ 'archive-dropdown' ] ) );
  }
}