Trigger event when clicking a paticular option value - javascript

I was wondering if the following is possible. I would like to fire different events depending upon which option is selected in a dropdown. So far I thought of this but nothing is happening when I select the option
$('#strand_id option[value="5"]:selected').on('click', function(){
console.log('something just happened!!!')
});
I don’t think I can use the change method as this will apply the same event no matter what option is selected (unless there is a way?).

Try this:
$('#strand_id').on('click ', function () {
if (this.value == 5) console.log('something just happened !! !')
});
jsFiddle example

Related

Select selected option again

I have a table and I use select menu in each row for different actions for that specific row.
For example:
$(document).on('change', '.lead-action', function() {
// Do stuff
}
this method gets the value of the selected option. Based on the selected value, I display different popups. When the user leaves the page, the select menu retains the previously selected option.
Sometimes users click on the same option in the select menu. When they do, the above code doesn't work.
Is there a way to invoke the code block above if the same option in the select menu is selected?
I'm gathering that you just want the dropdown to fire anytime a selection is made. If so, check out the answer to Fire event each time a DropDownList item is selected with jQuery.
See my updated answer below:
You can use this small extension:
$.fn.selected = function(fn) {
return this.each(function() {
var clicknum = 0;
$(this).click(function() {
clicknum++;
if (clicknum == 2) {
clicknum = 0;
fn(this);
}
});
});
}
Then call like this:
$(".lead-action").selected(function(e) {
alert('You selected ' + $(e).val());
});
Update:
I'm actually rather unhappy with the original script. It will break in a lot of situations, and any solution that relies on checking the click count twice will be very fickle.
Some scenarios to consider:
If you click on, then off, then back on, it will count both clicks and fire.
In firefox, you can open the menu with a single mouse click and drag to the chosen option without ever lifting up your mouse.
If you use any combination of keyboard strokes you are likely to get the click counter out of sync or miss the change event altogether.
You can open the dropdown with Alt+↕ (or the Spacebar in Chrome and Opera).
When the dropdown has focus, any of the arrow keys will change the selection
When the dropdown menu is open, clicking Tab or Enter will make a selection
Here's a more comprehensive extension I just came up with:
The most robust way to see if an option was selected is to use the change event, which you can handle with jQuery's .change() handler.
The only remaining thing to do is determine if the original element was selected again.
This has been asked a lot (one, two, three) without a great answer in any situation.
The simplest thing to do would be to check to see if there was a click or keyup event on the option:selected element BUT Chrome, IE, and Safari don't seem to support events on option elements, even though they are referenced in the w3c recommendation
Inside the Select element is a black box. If you listen to events on it, you can't even tell on which element the event occurred or whether the list was open or not.
The next best thing is to handle the blur event. This will indicate that the user has focused on the dropdown (perhaps seen the list, perhaps not) and made a decision that they would like to stick with the original value. To continue handling changes right away we'll still subscribe to the change event. And to ensure we don't double count, we'll set a flag if the change event was raised so we don't fire back twice:
Updated example in jsFiddle
(function ($) {
$.fn.selected = function (fn) {
return this.each(function () {
var changed = false;
$(this).focus(function () {
changed = false;
}).change(function () {
changed = true;
fn(this);
}).blur(function (e) {
if (!changed) {
fn(this);
}
});
});
};
})(jQuery);
Instead of relying on change() for this use mouseup() -
$(document).on('mouseup', '.lead-action', function() {
// Do stuff
}
That way, if they re-select, you'll get an event you can handle.
http://jsfiddle.net/jayblanchard/Hgd5z/

.on change function works first time not second?

I have a shopping cart that calculates cost and shipping based on quantity and weight. Because of this there are two possible shipping options and I have a function to auto-select the correct shipping on page load. However, if a person changes the quantity the function to select the shipping must run again.
To do this I tried this code:
$('.cartInputText').on('change', function() {
$('#ShippingOptions option').each(function(){
if (this.value == '163182') {
$('#ShippingOptions option[value="163182"]').prop('selected', true)
return false;
}
if (this.value == '163183') {
$('#ShippingOptions option[value="163183"]').prop('selected', true)
return false;
}
});
});
This works the first time I change the quantity. If I change the quantity a second time it doesn't work. How do I fix this so no matter how many times I change the quantity it works?
Update
The onchange event fires the first time but does not fire the second time. Why?
Please use live instead of on, or if the version of jQUery is higher than 1.9, please make you code like this: $(document).on('change','.cartInputText',function(){});
For your sample code, you only bind the function to .cartInputText, if the page re-renders or whatever the reason cause .cartInputText re-generate, it loses the function.
For my code, I bind the function to document and I think you know the event of html element can bubble, you click on .cartInputText and it bubbles up to document and let the function be triggered. More, please check Live and Bind difference in jQuery.
User KeyUp function instead of change for detecting input text.
Like:
$('.cartInputText').keyup(function () {
alert('test');
});
Here's the official jQuery documentation for .keyup().
DEMO
the above code works for the html code which is added before executing the previous statements,
if some other content with the same class (cartInputText) is added dynamically
you need to assign above functionality by calling it again after adding the content.

How to check if dropdown is open in Select2?

I'm using select2 and in my site. I need to know at some point if the dropdown is open or closed. I've studied the documentation but I don't see how this can be done. For example, something like this would be nice:
if ($('select').select2('isOpen') === true) { ... }
Any suggestions?
In version 4.0 of select2 you can listen to select2:opening, select2:open, select2:closing and select2:close events on select element, for example:
$('select').on('select2:open', function (e) {
// select2 is opened, handle event
});
Select2 4.0 has an isOpen method. If #mySelect is your HTML select element then:
$('#mySelect').data('select2').isOpen()
...will return true or false depending on the state of Select2.
By doing some code inspection, it looks like select2-dropdown-open is the class that it adds. But there is an event select2-open in the documentation that fires when the dropdown is open. You can use that to set a variable, or perform an action (also select2-close).
You can do something like this:
$("#e11").on("select2-open", function() {
$(this).data("open", true);
});
$("#e11").on("select2-close", function() {
$(this).data("open", false);
});
if ($("#e11").data("open")) {
//do something
}
2018 Edit
It appears that the names of the events have been updated since 2014. See user1636505's answer below.
As of Select2 4.0.6, this has been updated to the following
$("#foo").select2("isOpen")
This will return true/false
Hope this helps!
change is fired whenever an option is selected or removed.
select2:open is fired whenever the dropdown is opened. select2:opening is fired before this and can be prevented.
select2:close is fired whenever the dropdown is closed. select2:closing is fired before this and can be prevented.
select2:select is fired whenever a result is selected. select2:selecting is fired before this and can be prevented.
select2:unselect is fired whenever a result is unselected. select2:unselecting is fired before this and can be prevented.
It's better to do this:
var select2 = $('#selectorname').data('select2');
if (select2.opened()) {
//do it
} else {
//dont do it
}
$('select').select2('isFocused');
https://github.com/select2/select2/issues/39
It works perfectly.
$(".select2-container").is(":visible")

Safer Way to Detect a SelectBox selection

I was asked to refresh a page (and it's data) based on the user's selection of an option in a select box.
I know that using the onChange event is the standard way to detect that a user changed their selection in a selectbox and I've done this a lot:
$("#provider").change(function(){
var selectedprovider = $('#provider').val();
//... Do something
});
I've also seen cases where certain browsers (IE) fire change events when a mouse wheel or arrow keys are being used to interact with the selectbox, not the actual event of changing an option selection.
Is there a better way to deal with this kind of scenario? For example checking to see if the array index of the selected option has changed? Not sure that there is an event for that specifically.
I am thinking it might be best to simply add a submit button next to the select box and stop trying to rely on the onChange event for select boxes.
How are you all handling this scenario?
One way would be to check to see if the value has actually changed at all since you registered your event. That would be one way to determine if the value is different or not.
Here's an example: http://jsfiddle.net/p9v7x/1/
$(function () {
var lastVal = $('#target').val();
$('#target').on('change', function () {
var self = $(this);
if (self.val() === lastVal) {
// don't do anything if it's the same:
console.log('same!');
} else {
// only do your action in this case:
console.log(self.val());
}
});
});

HTML dropdown can't capture onChange() if there is only one value in dropdown

I am using Jquery, for selecting value of drop-down.
I need do do some action on OnChange event (.change in jQuery) , but if there is only one option in drop-down I am not able to capture it in onChange event.
My drop-down is formed dynamically, so don't know how many options I'll get how many options, but I am facing problem if there is just one option.
Is there any way to capture OnChange event for <select> with only one <option>?
You don't need to have an onchange event. Just have a function that gets called from onchange, and if there is only one item, just go ahead and call that function.
function populate() {
//do work to populate #selector
if($("#selector option").length == 1) {
$("#selector").hide();
workerFunction();
} else {
$("#selector").show();
}
$("#selector").change(workerFunction);
//the following line of code will work like a default:
workerFunction();
}
function workerFunction() {
//put whatever used to be in your onChange function here
}
onchange event occurs when the internal state of the element is changed. Since you have a dropdown with a unique value, its state is never changed so the event is not fired.
<label for="checkboxThatUsedToBeASelect">
<input type="checkbox" id="checkboxThatUsedToBeASelect" name="checkboxThatUsedToBeASelect" value="something" />
</label>
$('#checkboxThatUsedToBeASelect').change( function(){
});
Now you have a more user-friendly input, and it'll trigger the change when it is checked or unchecked. :D
How about a conditional event binder? Something like:
var changeHandler = function (method) {
alert(method);
};
if ($('select option').length > 1) {
$('select').change(function() {
changeHandler('change');
});
} else {
$('select').click(function() {
changeHandler('click');
});
}
It sounds like you have a HTML error in your options tags.
In addition to that, in order to target something created dinamically with jQuery, you have to use delegators.
$('selector').change( function(e){...}); // without delegator
$('body').on('change','selector', function(e){...}); // with delegator, it detects even an element added dinamically
This said, you should be abble to detect on change for new and old elements
.change looks for another inmate to switch places. in your case sadly, there is a home alone case and hence the event is not firing.

Categories