Home > Blockchain >  How to get Select2 to to use value and not options
How to get Select2 to to use value and not options

Time:08-27

Hi I have search all ower and cannot get the correct answer or help

I want to ake the select2 display the value and not the option text but cannot get it to work

this is what I have

<select  name="upsell-edit-select" multiple="" style="width: 100%;" tabindex="-1" aria-hidden="true">
<option value="1">Cat 1</option>
<option value="2">Cat 2</option>
<option value="3">Cat 3</option>
<option value="4">Cat 4</option>
</select>

<?php
      $args = array( 'order'      => 'ASC',
    'hide_empty' => $hide_empty,
    'include'    => $ids,
    'posts_per_page' =>'-1'
);
$product_categories = get_terms( 'product_cat', $args );
echo '<select  name="upsell-edit-select" multiple="multiple" style="width: 100%;">';
foreach( $product_categories as $category ){
    echo "<option value = '" . esc_attr( $category->slug ) . "'>". esc_html( $category->name ) . "</option>";
   // echo "<option value = '" . esc_html( $category->name ) . "'>" . esc_html( $category->name ) . "</option>";
}
echo "</select><br/>";
    
        ?>
<script type="text/javascript">   
jQuery(document).ready(function()  {
  // turn the element to select2 select style
  jQuery('.test-basic-multiple').select2({
    placeholder: "Select Categories",
    maximumSelectionLength: 3,
    tokenSeparators: [',', ' ', ';'],
    allowClear: true,
  }).on('change', function(e) {
    var data = jQuery(".test-basic-multiple option:selected").map((i,e) => jQuery(e).text()).toArray();
    jQuery("#test").val(data.join(', '));
    });
});


<input name="sell" type="text" value="<?php echo esc_attr($sell); ?>" id="test" readonly>

Now it works it displays the selected category name but not the value what do I change to make it show the value or slug ?

CodePudding user response:

Try val() instead of text()

var data = jQuery(".test-basic-multiple option:selected").map((i,e) => jQuery(e).val()).toArray();
  • Related