Multiple Select - Chosen jQuery
-
03-06-2021 - |
Domanda
I am using the Harvest Chosen jQuery plugin successfully to create a drop down single selection list with a submit button on a Wordpress site. This is connected up to display all terms from a given taxonomy, and allows a user to choose a term and then press a submit button to load the corresponding page relating to the selected term.
I am now trying to get the plugin to work with multiple selections of terms from the taxonomy. I have the selection working and on the front-end a user can select multiple terms, but I cannot figure out how to submit the multiple selections.
I know my code is missing something, but I can't figure out what needs modifying to allow multiple terms to be selected.
This is what I have so far:
<form action="<?php bloginfo('url'); ?>">
<div>
<?php
function get_terms_dropdown($taxonomies, $args){
$myterms = get_terms($taxonomies, $args);
$output ="<select name='topics' class='chosen' style='width:500px' multiple='true'>";
foreach($myterms as $term){
$root_url = get_bloginfo('url');
$term_taxonomy = $term->taxonomy;
$term_slug = $term->slug;
$term_name = $term->name;
$link = $term_slug;
$output .="<option value='".$link."'>".$term_name."</option>";
}
$output .="</select>";
return $output;
}
$taxonomies = array('topics');
$args = array();
echo get_terms_dropdown($taxonomies, $args);
?>
<div><input type="submit" value="Filter" /></div>
</div>
</form>
Ordinarily, for multiple selections, the URL structure would look like the following for an 'AND' query:
domain.com/?topics=topic1+topic2+topic3
OR the following for an 'OR' query:
domain.com/?topics=topic1,topic2,topic3
Getting either of these options would work for now (I eventually intend to add an option for AND/OR searches)
Any help or pointers in the right direction to get this working would be great.
Soluzione
When you submit the form, you could build the URL with JavaScript and change the page with something like:
$('form').submit( function() {
var selectArray = $('select').val();
var newURL = "http://domain.com/?topics=";
for (var i = 0; i < selectArray.length; i++) {
if ( 1 != 0 ) {
newURL += "+";
}
newURL += selectArray[i];
}
window.location = newURL;
});
Breakdown: $('form').submit( function() { [...] });
gets fired when a form is submitted. You would want to qualify this with a class $('form.yourClass')
or ID $('form#yourID')
unique to your form.
$('select').val()
will return an array of the selected values for a selet element. It should be qualified in the same way as the form with a class $('select.yourClass')
or an ID $('select#yourID')
. The JavaScript goes through the array and appends each value to the root URL of http://domain.com/?topics=
with a +
in between each value. Once it is done, the user is redirected to the new URL.