Reputation: 5501
I am facing a issue that I want the select value on click event. i tried with change
event but I get all values comma separated instead of current value.
What I want to do is, Suppose there are multiple options with a All
option. So if a user select All
option then it should clear all selected option and only All
option will display.
I have tried below codes
$(".chzn-select").on('select2:selecting', function () {
var st = ($(this).select2('val'));
}
it show null
on first click.
And
$(".chzn-select").on('change', function () {
var st = ($(this).select2('val'));
}
show all values in comma separated format. There is no example I found of onclick
event with select2
JS. Here is the list of events
HTML
<select name="country[]" multiple="" data-placeholder="Select country" class="form-control chzn-select" required="required" id="country">
<option disabled="disabled" value="1">Abu Dhabi</option>
<option value="2">Dubai</option>
<option disabled="disabled" value="3">Singapore</option>
<option disabled="disabled" value="4">Thailand</option>
<option value="8">Afghanistan</option>
<option value="All">All</option>
</select>
Here is the jsfiddle
Upvotes: 0
Views: 8796
Reputation: 1078
https://jsfiddle.net/bayahiassem/gtew005w/11/
$(".chzn-select").select2({selectOnClose: true}).on("select2:selecting", function(evt) {
if(evt.params.args.data.id == 'All') {
$(".chzn-select").val(null).trigger("change");
} else {
$('.chzn-select > option[value=All]').prop("selected", false);
}
});
Upvotes: 2
Reputation: 18577
I hope this will work,
$(".chzn-select").select2({selectOnClose: true});
$(".chzn-select").on("select2:select", function (evt) {
if($.inArray('All',$(this).val()) != -1){
$(this).val('All').trigger("change");
}
});
Replace your js code with this, it will work.
Here is jsfiddle link for working code.
Upvotes: 0
Reputation: 4025
Here you are. It will you give the current selected item(s) - hold ctrl for multiple selections
$(function () {
$(".chzn-select").on('change', function (evt) {
$('#selected').text('Selected: ' + ($(this).val()))
})
})
select {
width: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="country[]" multiple="" data-placeholder="Select country" class="form-control chzn-select" required="required" id="country">
<option disabled="disabled" value="1">Abu Dhabi</option>
<option value="2">Dubai</option>
<option disabled="disabled" value="3">Singapore</option>
<option disabled="disabled" value="4">Thailand</option>
<option value="8">Afghanistan</option>
<option value="All">All</option>
</select>
<div id="selected"></div>
Upvotes: 0
Reputation: 798
I didn't get you. If i correct.
$(this).select2('val').find(':selected');
Upvotes: 0