Select2 Dropdown Multiple select and unselect - javascript

I have a select2 dropdown with 4 options code is:
<select id="ddlInqOn" class="InqSelect2 form-control">
<option value="1">--All--</option>
<option value="2">Today Date</option>
<option value="3">Past Date</option>
<option value="4">Feature Date</option>
</select>
select2 called by this javascript:
$('.InqSelect2').select2({
dropdownAutoWidth: 'true',
multiple: true
});
I want to achieve like when I click all option then remove other options and if other option is selected then remove all option from selection.
I have tried this code:
$('body').on('change', '#ddlInqOn', function() {
debugger;
//
});
but the change event is not triggred so any other possibility to track change event of select2 dropdown?

Select2 uses the jQuery event system. So you can attach to the select2 events using the JQuery on method.
Then you can set the value of the select element and trigger the change event to update the select box.
You can do what you have asked in following way.
$('.InqSelect2').on('select2:select', function (e) {
if (e.params.data.id == 1){
$(this).val(1).trigger('change');
}else{
values = $(this).val();
var index = values.indexOf('1');
if (index > -1) {
values.splice(index, 1);
$(this).val(values).trigger('change');
}
}
});
Note that I have used '1' as the value of --All-- option. Feel free to ask me anything if it's not clear to you.
https://jsfiddle.net/c6yrLoow/
Hope it helps :)

Answer given by #Nimeksha works perfectly in jsfiddle given by # Nimeshka but in my code i cant get trigger event of change in dropdown and after searching i found solution from here. the code is here :
$(document).on('change', '.InqSelect2', function () {
debugger;
if (e.params.data.id == 1) {
$(this).val(1).trigger('change');
} else {
values = $(this).val();
var index = values.indexOf('1');
if (index > -1) {
values.splice(index, 1);
$(this).val(values).trigger('change');
}
}
});
i have also tried :
$('body').on('change', '.InqSelect2', function () {
debugger;
if (e.params.data.id == 1) {
$(this).val(1).trigger('change');
} else {
values = $(this).val();
var index = values.indexOf('1');
if (index > -1) {
values.splice(index, 1);
$(this).val(values).trigger('change');
}
}
});
but it doesn't work. also by id #ddlInqOn does not work.
why above code worked with $(document).on('change', '.InqSelect2', function () {}); worked i dont know but it works for me.
thanks again #Nimeshka

Related

Jquery selected option text contains

Trying to make if condition of selected option of another select not the current which contains certain text string as a text and not the value.
Example:
<select class="Selected">
<option>Hello</option>
<option>Bye</option>
</select>
In the following case what I have is the fowling. a trigger of another select:
$(".Selected_Two").change(function () {
if ($(this).closest('.div-block').find('.Selected:contains("Bye")')) {
alert('Bye');
}
});
So basically if the select option is selected in the select when triggering the other select will have to see alert "Bye"
But it is not working at this state. Any help is welcome.
Two ways to do that indexOf() for value or :contains for option text
indexOf()
$(".Selected_Two").change(function () {
var SelectTwoValue = $(this).val();
if ($(this).closest('.div-block').find('.Selected)').val().indexOf(SelectTwoValue ) > -1) {
alert('Bye');
}
});
:contains and length
$(".Selected_Two").change(function () {
var SelectTwoValue = $(this).val();
if ($(this).closest('.div-block').find('.Selected option:selected:contains("'+SelectTwoValue+'")').length > 0) {
alert('Bye');
}
});
Maybe you'll need to work around .val().indexOf() and :contains("'+SelectTwoValue+'")').length .. but I think you got the point

Select option won't fire jquery event

I'm having some problems with what should be a simple jQuery show/hide based on a select's value. The select is hidden by default based on other selects, which might be why it's not working?
Unfortunately I can't change the source code in any manner, I can only add a function like this.
$(document).ready(function() {
$('#question-select-1271443').change(function() {
var selection = $(this).val();
if (selection == 'CIIC') {
$('#question-select-1082380').show();
} else {
$('#question-select-1082380').hide();
}
});
});
function val() extract the value of the attribute value of the option selected. Maybe you are trying to extract the content of the option. Example:
<select id="sas">
<option value="hi">Hello</option>
</select>
$("#sas").change(function(){
$(this).val(); // This return hi
$("option:selected", this).text() // This return Hello
});

How can I change selected value of a DropDownList with having change method?

I was wondering if it's possible to get jQuery to select an option with having predefined change method.
Let me give me an example; I have a drop-down list like this:
<select id="ddl_BankRequestType">
<option>-- Request Type ---</option>
<option value="val1">Item1</option>
<option value="val2">Item2</option>
</select>
If user selects Item1 or Item2 some logic will be executed:
$('#ddl_BankRequestType').change(function () {
var selectedItem = $(this).find(":selected").text();
if (selectedItem === 'Item1') {
// codes
} else if (selectedItem === 'Item2') {
//other codes
}
});
It works like a charm. Now in document.ready I want the second option be selected item, so I put this code:
$('#ddl_BankRequestType > option:eq(2)').attr('selected', true);
It also works, but I want the logic for Item2 to execute. I have tried the following, but they do nothing:
$('#ddl_BankRequestType > option:eq(2)').attr('selected', true).change();
$('#ddl_BankRequestType > option:eq(2)').attr('selected', true).trigger('change');
You can check the code from DEMO
$(function (){
$('#ddl_BankRequestType').change(function () {
var selectedItem = $(this).find(":selected").text();
console.log(selectedItem)
if (selectedItem === 'Item1') {
alert('item1');
} else if (selectedItem === 'Item2') {
alert('item2');
}
});
$('#ddl_BankRequestType > option:eq(2)').attr('selected', true).change();
});
A quick fix should be something like below,
$('#ddl_BankRequestType').on("change",function () {
var selectedItem = $(this).find(":selected").text();
if (selectedItem === 'Item1') {
doItem1();
} else if (selectedItem === 'Item2') {
doItem2();
}
});
function doItem1(){
alert('Item1');
//other codes
}
function doItem2(){
alert('Item2');
//other codes
}
$(document).ready(function(){
$('#ddl_BankRequestType > option:eq(2)').attr('selected', true);
doItem2();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ddl_BankRequestType">
<option>-- Request Type ---</option>
<option value="val1">Item1</option>
<option value="val2">Item2</option>
</select>
The problem is .attr() returns a string. So, you can't chain it to trigger the change event. You could do the following:
var ddl_BankRequestType = $('#ddl_BankRequestType');
ddl_BankRequestType.find('option:eq(2)').attr('selected', true);
ddl_BankRequestType.trigger('change');
This is likely a timing issue - since theoretically your code should be firing that trigger event based on the way you're doing it. I think it's simply firing the event before the change function is registered. jQuery's Document load lifecycle loops through all of the defined loaders in the order they're registered, so if you're not able to change when you set the option element as "selected" to after the change event is bound, you may be able to use the native timeout function to ensure it gets fired last.
I generally avoid using timeout like this, but in your scenario it may work:
setTimeout(function() { /* Set the option element true here */ }, 1000);
Best bet is to try and set the element after the change event is bound.

How to fill a select element which is not embedded in a form with CasperJS?

My html code is:
<div class="setting-control">
<select class="on-off" id="custom-cache-pref">
<option value="">Default</option>
<option value="byc">Bypass cache</option>
<option value="basic">Basic caching</option>
<option value="iqs">Ignore query string</option>
<option value="agg">Aggressive caching</option>
<option value="all">Cache everything</option>
</select>
</div>
Usually with casperjs I would use
this.fillSelectors('form[name="formName"]', {
'select[id="custom-cache-pref"]': 'byc'
}, false);
to select option "byc" but this time the "select" element is not embedded in a form!
How can I choose its value in this case?
Adapted from my answer here, you can create your own function that selects an option by value. This changes the selected index which might not trigger the select onChange event.
casper.selectOptionByValue = function(selector, valueToMatch){
this.evaluate(function(selector, valueToMatch){
var select = document.querySelector(selector),
found = false;
Array.prototype.forEach.call(select.children, function(opt, i){
if (!found && opt.value.indexOf(valueToMatch) !== -1) {
select.selectedIndex = i;
found = true;
}
});
// dispatch change event in case there is some kind of validation
var evt = document.createEvent("UIEvents"); // or "HTMLEvents"
evt.initUIEvent("change", true, true);
select.dispatchEvent(evt);
}, selector, valueToMatch);
};
casper.start(url, function() {
this.selectOptionByValue('select#custom-cache-pref', "byc");
}).run();
Alternative 1
Judging by the code of __utils__.fill() and casper.fillForm(), the selector of the form doesn't necessarily have to be a form. It may be a div:
this.fillSelectors('div.setting-control', {
'select[id="custom-cache-pref"]': 'byc'
}, false);
Alternative 2
If this still doesn't work, you might need to resort on focusing on the select element in the page context and sending up and down key events to change the value using PhantomJS' page.sendEvent():
this.evaluate(function(){
document.querySelector('select[id="custom-cache-pref"]').focus();
});
this.page.sendEvent('keypress', this.page.event.key.Down);

Detect when a specific <option> is selected with jQuery

I'd like jQuery to detect when the option with the id trade_buy_max is selected.
$(document).ready(function() {
$("option#trade_buy_max").select(function () {
//do something
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<select name='type' id='type'>
<option id='trade_buy' value='1' selected='selected'>Buy</option>
<option id='trade_buy_max' value='1'>Buy max</option>
<option id='trade_sell' value='2'>Sell</option>
<option id='trade_sell_max' value='2'>Sell max</option>
</select>
I've tried the following, but it doesn't seem to work.
Any ideas?
This works...
Listen for the change event on the select box to fire and once it does then just pull the id attribute of the selected option.
$("#type").change(function(){
var id = $(this).find("option:selected").attr("id");
switch (id){
case "trade_buy_max":
// do something here
break;
}
});
What you need to do is add an onchange handler to the select:
$('#type').change(function(){
if($(this).val() == 2){
/* Do Something */
}
});
you can bind change event on its select instead, then check if option selected
$("select#type").change(function () {
if( $("option#trade_buy_max:selected").length )
{
// do something here
}
});
$("option#trade_buy_max").change(function () {
opt = $(this).children("option:selected").attr('id');
if(opt == '#trade_sell_max'){
// do stuff
}
});
Untested, but that should work.
Use the change event and get the id attribute of the selected option:
$('#type').change(function () {
var selectedId = $('option:selected', this).attr('id');
if (selectedId == "trade_buy_max") {
// do something
}
});
Change .select to .change and put space before #

Categories