PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 26, 2022

[FIXED] How to get Select2 to to use value and not options

 August 26, 2022     php, woocommerce, wordpress     No comments   

Issue

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 class="test-basic-multiple select2-hidden-accessible" 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 class="upsell-basic-multiple" 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 ?


Solution

Try val() instead of text()

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


Answered By - Vasanth Ramesh
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing