简体   繁体   中英

Select option tag using jquery

I have a drop down form that when I select an option should show the photos with those tags. This code works fine when I make the option tags into divs or ul/li elements. While I know the function works with those, it will not work when I have them as select/option elements.

I theorize that the problem exists within the click function, yet am unable to solve. Other jquery functions for forms offer no solution as well.

Any assistance is appreciated.

HTML/PHP

<form>
  <select id="industry_area">Industry:

    <option class="active industry" id="all">All</option>
        <?php
        // check if the repeater field has rows of data

                // loop through the rows of data
            while ( have_rows( 'industry_menu' ) ) :
                the_row();

                // display a sub field value
                        $industry_menu = get_sub_field( 'industry_field_name' );
                        $count = get_row_index();
                        echo "<option class='industry' id=$industry_menu> $industry_menu </option>";

                    endwhile;

        ?>

  </select>
</form>


<div id="parent">
    <?php
    foreach ( $partners as $partner ) {
        $id      = $partner->ID;
        $image   = get_the_post_thumbnail($id);
        $vip = get_field('vip', $id);
        $industry_type = get_field('industry', $id);
        $industry_type_string = $industry_type[0];
        echo
        "<div class='item $vip $industry_type_string'>
            $image
        </div>";
    }
    ?>
</div>


JS

  var $industry = $('.industry').click(function() {
    if (this.id == 'all') {
      $('#parent > div').fadeIn(450);
    } else {
      var $el = $('.' + this.id).fadeIn(450);
      $('#parent > div').not($el).hide();
    }
    $industry.removeClass('active');
    $(this).addClass('active');
    })

Photo: screeshot

You cannot give <option> tags an id attribute. They dont have one.

Instead give the <select> tag an id like you have <select id="industry_area"> then as you have no index attribute set on the <option> tags, you will have to use jquery code like this to get the selected text

$( "#industry_area option:selected" ).text();

You code amended

var $industry = $('.industry_area ').click(function() {
    if ($( "#industry_area option:selected" ).text() == 'all') {
        $('#parent > div').fadeIn(450);
    } else {
        var $el = $('.' + this.id).fadeIn(450);
        $('#parent > div').not($el).hide();
    }
    $( "#industry_area option:selected" )
        .removeClass('active')
        .addClass('active');
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM