Reputation: 370
I use select2, and i want to get the value of my option when i select a tag, but my select2 output is like that
"span" "UL" "li" and when i search here i found one say that you can get your value of option like this jQuery("#service").select2('data');
but i get a empty alert
html:
<div class="wpb_column vc_column_container vc_col-sm-3">
<input type="hidden" value="search" class="search_icon">
</div>
<div class="wpb_column vc_column_container vc_col-sm-5">
<label class="control-label col-md-3">Que cherchez-vous ?</label>
<select name="services[]" id="service" class="form-control select2-multiple col-lg-5 col-md-9" multiple>
<?php if ( !empty( $post_id ) ) {
foreach ($post_id as $value) {
?>
<option value="<?php echo($value->ID);?>"><?php echo($value->post_title);?></option>
<?php
}
}
?>
</select>
</div>
<div class="wpb_column vc_column_container vc_col-sm-2">
<input type="button" value="search" class="search_icon">
</div>
<div class="wpb_column vc_column_container vc_col-sm-3">
<input type="hidden" value="search">
</div>
and this my script :
<script>
jQuery(document).ready(function() {
jQuery('#service').select2({
minimumInputLength: 1,
width: '100%',
tags: true
});
var option_val = jQuery("#service").select2('data');
jQuery('.search_icon').on('click', function() {
alert(option_val);
});
</script>
Upvotes: 1
Views: 1628
Reputation: 67525
To retrieve the current selected value in the list when you click you have to use select2('data')
inside the click event like :
jQuery('.search_icon').on('click', function() {
var option_val = jQuery("#service").select2('data');
alert(option_val[0].text); //text
//Or
//alert( jQuery("#service option:selected").text() ); //text
//Or
//alert( jQuery("#service").val() ); //value
});
Upvotes: 1