Unable to bind onChange event with select - javascript

I am trying to bind on-change event with my HTML select , but not successful in this,
This is my HTML code
<div class="size clearfix">
<form>
<label for="Size"><spring:theme code="product.variants.size"/></label>
<select id="Size">
<option>..</option>
<option>..</option>
<option>..</option>
</select>
</form>
</div>
And this is how, I am trying to bind onChange event
$(document).ready(function ()
$("#Size").change(function () {
var url = "";
var selectedIndex = 0;
$("#Size option:selected").each(function () {
url = $(this).attr('value');
selectedIndex = $(this).attr("index");
});
if (selectedIndex != 0) {
window.location.href=url;
}
});
});
But somehow this is not working, not sure what I am doing wrong.Just to add all this code is in $(document).ready(function ()
By not working means, event is not getting fired at all

There is no index attribute, you should read the selectedIndex property of the select element.
var selectedIndex = this.selectedIndex;
Also since you don't have a multiple select element, the each call here is redundant. this.value gives you the current select's value.
$("#Size").change(function () {
if (this.selectedIndex > 0) {
// Assuming your options have `value` attribute
window.location.href= this.value;
}
});
For the sake of completeness for getting the index of the selected option in the each callback you could use the index method:
$(this).index();
Since attr('index') returns an undefined value your condition is always falsy.

Related

Select2 Dropdown Multiple select and unselect

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

How to apply reset button only to each select instead of all filtering options in Mixitup?

Here's my code: http://codepen.io/kikibres/pen/mVYOaR
I’m trying to recode the select options to display the “X” button when it’s selected and when one click on the “X” button, it reset back to the original select value. Additionally, I wanted the "x" button to work only on their own dropdown menu instead of all dropdown menus.
I’m trying to make it more similar to http://www.mtommaneycentre.com.au/stores/. As you can see, when you click on an option in “A-Z” select field, an “X” button appears and when you click on the “X” button, it reset to the original “A-Z” select option….
How do one do that?
HTML
<div class="filtermenu">
<form class="controls" id="Filters">
<fieldset class="select-style">
<select>
<option value="">All</option>
<option value=".triangle">Triangle</option>
<option value=".square">Square</option>
<option value=".circle">Circle</option>
</select>
<button class="btn-clear">x</button>
</fieldset>
<fieldset class="select-style">
<select>
<option value="">All</option>
<option value=".blue">Blue</option>
<option value=".white">White</option>
<option value=".green">Green</option>
</select>
<button class="btn-clear">x</button>
</fieldset>
<fieldset>
<button class="filter" data-filter=".triangle">Triangle</button>
</fieldset>
<fieldset>
<input type="text" placeholder="Enter Name" val="" data-filter="" id="filter--text" />
</fieldset>
<button id="Reset">Clear Filters</button>
</form>
</div>
Javascript
The code that reset all options is
self.$reset.on('click', function(e){
e.preventDefault();
in
var dropdownFilter = {
// Declare any variables we will need as properties of the object
$filters: null,
$reset: null,
groups: [],
outputArray: [],
outputString: '',
// The "init" method will run on document ready and cache any jQuery objects we will need.
init: function(){
var self = this; // As a best practice, in each method we will asign "this" to the variable "self" so that it remains scope-agnostic. We will use it to refer to the parent "dropdownFilter" object so that we can share methods and properties between all parts of the object.
self.$filters = $('#Filters');
self.$reset = $('#Reset');
self.$container = $('#Container');
self.$filters.find('fieldset').each(function(){
var $this = $(this);
self.groups.push({
$buttons : $this.find('.filter'),
$inputsSelect : $this.find('select'),
$inputsText : $this.find('input[type="text"]'),
active : ''
});
});
self.bindHandlers();
},
// The "bindHandlers" method will listen for whenever a select is changed.
bindHandlers: function(){
var self = this;
// Handle select change
self.$filters.on('click', '.filter', function(e){
e.preventDefault();
var $button = $(this);
// If the button is active, remove the active class, else make active and deactivate others.
$button.hasClass('active') ?
$button.removeClass('active') :
$button.addClass('active').siblings('.filter').removeClass('active');
self.parseFilters();
});
// Handle dropdown change
self.$filters.on('change', function(){
self.parseFilters();
});
// Handle key up on inputs
self.$filters.on('keyup', 'input[type="text"]', function() {
var $input = $(this);
console.log($input.val());
$input.attr('data-filter', '[class*="'+$input.val().replace(/ /, '-')+'"]');
if ($input.val() == '')
$input.attr('data-filter', '');
console.log($input.attr('data-filter'));
self.parseFilters();
});
// Handle reset click
self.$reset.on('click', function(e){
e.preventDefault();
self.$filters.find('.filter').removeClass('active');
self.$filters.find('.show-all').addClass('active');
self.$filters.find('select').val('');
self.$filters.find('input[type="text"]').val('').attr('data-filter', '');
self.parseFilters();
});
},
// The parseFilters method pulls the value of each active select option
parseFilters: function(){
var self = this;
// loop through each filter group and grap the value from each one.
for(var i = 0, group; group = self.groups[i]; i++){
var activeButtons = group.$buttons.length ? group.$buttons.filter('.active').attr('data-filter') || '' : '';
var activeSelect = group.$inputsSelect.length ? group.$inputsSelect.val() || '' : '';
var activeText = group.$inputsText.length ? group.$inputsText.attr('data-filter') : '';
group.active = activeButtons+activeSelect+activeText;
console.log(group.active);
}
self.concatenate();
},
// The "concatenate" method will crawl through each group, concatenating filters as desired:
concatenate: function(){
var self = this;
self.outputString = ''; // Reset output string
for(var i = 0, group; group = self.groups[i]; i++){
self.outputString += group.active;
}
// If the output string is empty, show all rather than none:
!self.outputString.length && (self.outputString = 'all');
console.log(self.outputString);
// ^ we can check the console here to take a look at the filter string that is produced
// Send the output string to MixItUp via the 'filter' method:
if(self.$container.mixItUp('isLoaded')){
self.$container.mixItUp('filter', self.outputString);
}
}
};
// On document ready, initialise our code.
$(function(){
// Initialize dropdownFilter code
dropdownFilter.init();
// Instantiate MixItUp
$('#Container').mixItUp({
controls: {
enable: false // we won't be needing these
},
callbacks: {
onMixFail: function(){
alert('No items were found matching the selected filters.');
}
}
});
});
At the moment there isn't attached any event handler to your "x" buttons, so if you click on them, it just refreshes the page, that's why it resets all filters, because it reinitialize all the code.
You should add this code to your plugin
$('.btn-clear').on('click', function(event) {
event.preventDefault();
$(this).prev().val("").change();
});
The event.preventDefault() will prevent to run the default event when you click on the button, which is to refresh the page in this case.
The next line will points to the previous DOM element of the clicked element (which is the <select>) and changes to the option which has the value: "", and after it triggers a change() event to tell your written code that the select's value is changed, so it should reload the figures with new filters.
I saved it here: http://codepen.io/anon/pen/EPzWEQ?editors=1010
Of Course you should implement it to your plugin, I just wrote it to the bottom of the code to make it work.
EDIT:
If you want to make invisible the X buttons if there is no filter selected, just make a 'change' event handler on the select, and check if value is "" then hide the button, else show it. It should be look like this:
$('select').change(function() {
if ($(this).val() == "") {
$(this).next().hide();
} else {
$(this).next().show();
}
});

in multiselect how can i get the clicked value using jquery

Multi Select Option i Get The Clicked Value Only Using jquery.
$(document).ready(function() {
$("#mySelect").change(function() {
var firstselected = $(':selected', this).val(); //returns first selected in list
var lastselected = $(':selected:last', this).val(); //return last selected in list
alert(firstselected);
alert(lastselected);
// what if i want exact option i have clicked in list
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mySelect" class="selectpicker" multiple>
<option>Option1</option>
<option>Option2</option>
<option>Option3</option>
<option>Option4</option>
<option>Option5</option>
<option>Option6</option>
<option>Option7</option>
</select>
var firstselected = $(':selected', this).val();//this returns first selected in list
var lastselected = $(':selected:last', this).val();//this return last selected in list
what if i want exact option i have clicked in list whether it is in middle of selected options list
you can get both all selected and current selected value
$("#mySelect option").click(function (e) {
var all = $("#mySelect :selected").map(function () {
return this.value;
}).get(); // all selected value
if (all.indexOf(this.value) != -1) { // check the condition your selecting or unselected option
alert(this.value); // current selected element
}
});
NOTE: you can get all selected value using all variable, and you can get current selected value also
DEMO
You will need to bind events on option also:
$("#mySelect").on("click", "option", function () {
console.log($(this)); //this will log the clicked option.
});
Demo :http://jsfiddle.net/lotusgodkk/GCu2D/725/
This will give you all the option you have selected from the first to last.
$(':selected',this).each(function(i, selected){
alert($(selected).val());
});
But if you want to get only the option that is just can add click listener to the options.
$("#mySelect").on('click','option',function(){
alert($(this).val());
});
You can get the clicked value using the following solution:
$("#mySelect").on('change', function(e) {
e.currentTarget.value //should return you the currently selected option
});

Changing the value of a variable after an event

Right now in the below code the var selected doesn't change (it outputs the empty string i guess). I need you to help me change the selected variable so that the value should be the selected option all of the time (in the select element). I also want to be able to use that updated variable later in the code outside of the isSelected function.
var isSelected = (function(){
var selected = "";
return {
add : function(){
$("select").on("change", function(){
selected = $(this).val()
})
},
output : function(){
alert(selected)
}
}
})()
$("select").on("change", function(){
isSelected.add();
isSelected.output();
})
Thanks im trying my best to learn programing
var isSelected = (function(){
var selected = "";
return {
add : function(el){
selected = $(el).val();
},
output : function(){
alert(selected)
}
}
})()
$("select").on("change", function(e){
e.preventDefault()
isSelected.add(this);
isSelected.output();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="">Select combo</option>
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
<option value="Value3">Text3</option>
</select>
Use this keyword to get current object. Please check the solution, hope this is what you need
The problem is binding to the change event in the add() function. You've already captured the change event, so when add() runs, it adds another change handler, which won't be triggered until the next change event fires.
The solution is to pass the selected value to add() as an argument.
I also want to be able to use that updated variable later in the code
Simply add another function, something like getSelected() which returns the value.
var isSelected = (function(){
var selected = "";
return {
add : function(value){
selected = value;
},
output : function(){
alert(selected);
},
getSelected : function(){
return selected;
}
}
})();
$("select").on("change", function(){
isSelected.add(this.value);
isSelected.output();
var selected = isSelected.getSelected();
console.log(selected);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>

jQuery Option De-Select Event?

I would like to detect the event where an option is de-selected from a select element. So for instance, if my HTML is:
<select id="select_box">
<option value="1">Hot</option>
<option value="2">Cold</option>
<option value="3">Just Right</option>
</select>
And the second option is selected (value="2"), and then the user de-selects it by clicking on another option (such as value="3") or clicking the same option again, how do I detect that event using jQuery? My goal is to fire off a function when it happens.
I tried the following:
$("#select_box option:selected").change(function() {
console.log($(this).val());
});
But it didn't work.
The change event should go on the select element itself:
$("#select_box").change(function() {
console.log($(this).val());
});
This event fires when the value of the select is changed and will match the behaviour you require.
I want the value of the option that was de-selected.
In that case you would need to store the previous value when it's selected, something like this:
$("#select_box").change(function() {
var $select = $(this),
currentValue = $select.val(),
oldValue = $select.data('previous-value');
// do stuff...
$select.data('previous-value', currentValue);
});
Well, this is how I would handle this with with a change Event listener.
$("#select_box").on('change', function(e){
var $t = $(this), data = $t.data('last') || {optText:'none', val:'none'};
$t.next().text('last was ['+data.optText+'] and its value is "'+data.val+'"').end()
.data('last', {optText:$t.children('[value="'+$t.val()+'"]').text(), val:$t.val()});
});
Fiddle HERE
I would enable the element when the option is selected using the one() event binding method
change event will fired only when value is changed which is required by you
$("#select_box").change(function() {
console.log(this.value);
});
You can do it manually some thing like below code i given,
var xSelectedOption = 0;
$("#select_box").change(function() {
if(xSelectedOption != $(this).val())
{
xSelectedOption = $(this).val();
console.log("Option was changed!");
}
});

Categories