Search code examples
phpjqueryhtmljquery-chosenjquery-ui-multiselect

How to get Chosen Multiselect selected values under the For Loop


This is my view file code

<?php for($i=0; $i<4; $i++)  { ?>
 <div class="box22">
      <div class="mcm">
           <input type="text" placeholder="Myself" id="coworkers" name="coworkers[]" />
           <span class="bar"></span>
      </div>

      <div class="select2">
       <select id="category_<?php echo $i; ?>" name="category[]" class="chosen-select ref-sel1" multiple >
           <?php
           foreach($genre as $gen){
                echo '<option value='.$gen->genre_id.'>'.$gen->genre_name.'</option>';
           } 
           ?>
       </select>
      </div>
 </div>
<?php } ?> 

my script : when i chose one or more from option, it does not comes into script. How to get multiple values under loop

    $(document).ready(function()
    {
        $('form#shortfilm').submit(function(e) 
        {
            e.preventDefault();
            var form = $(this);
            var foo = [];
            $('#category :selected').each(function(i, selected){
              foo[i] = $(selected).text();
            });
        });
    });

Solution

  • change text to val()

     $('option:selected').each(function(i, selected){
                  foo.push($(selected).val());
                });
    

    or:

    var foo = [];
    $('.box22').each(function(x,v){
    var temp =[]
         $(v).find('option:selected').each(function(i, selected){
            temp.push($(selected).val());
         });
         foo.push(temp)
    });
    

    see demo for the second option here