jQuery execute function when option is selected from option object - javascript

I am dynamically creating the options for a select element using jQuery. Is it possible in jQuery to setup a function to be executed when that option is selected?
I know I can detect the change of the entire select element, but is it possible to specify this on a per-option basis? Maybe something like this:
$('<option />').onselect(function(){
// do something
});
Edit:
If it's not possible to specify a function that get's executed when a specific option is selected, is it possible to bind a function to an element in jQuery? It would make my logic cleaner by allowing me to just simply execute that function assigned to the option in the .change for the select.

You can delegate a change event to the document and attach an event handler to the select element. This allows for runtime manipulation:
$(document).on('change', 'select', function() {
console.log($(this).val()); // the selected options’s value
// if you want to do stuff based on the OPTION element:
var opt = $(this).find('option:selected')[0];
// use switch or if/else etc.
});
Or if you insist on creating functions for each OPTION, you can do:
$('<option>').data('onselect', function() {
alert('I’m selected');
});
$(document).on('change', 'select', function(e) {
var selected = $(this).find('option:selected'),
handler = selected.data('onselect');
if ( typeof handler == 'function' ) {
handler.call(selected, e);
}
});

You can use onchange handler to the select:
<select name='numbers' id='numbers'>
<option value='1' selected='selected'>One</option>
<option value='2'>two</option>
<option value='3'>three</option>
<option value='4'>four</option>
</select>
<script>
$('#numbers').change(function () {
if ($(this).val() === '1'){
function1();
}
if ($(this).val() === '2'){
function2();
}
});
</script>
Best Regards

What you can try is binding the change() event on the select element itself. From there, assuming you have a valid function for each option, you can call an individual option's callback:
$('select').change(function() {
var type = $(this).val();
switch(type) {
}
// Alternatively, you can try this as well:
$(this).find('option:selected').each(function() {
});
});

If you are saying you want to assign individual functions to each option element you can do something like this:
var options = [{"value" : "1",
"display" : "One",
"fn" : function() { console.log("One clicked"); }
},
{"value" : "2",
"display" : "Two",
"fn" : function() { console.log($(this).val() + " clicked"); }
}];
var $select = $("select").on("change", function() {
var opt = this.options[this.selectedIndex];
$(opt).data("fn").call(opt);
});
$.each(options, function(i, val) {
$select.append(
$("<option/>").attr("value", val.value)
.text(val.display)
.data("fn", val.fn)
);
});
​Demo: http://jsfiddle.net/6H6cu/
This actually attaches functions to each option using jQuery's .data() method, and then on click/keyup on the select element it calls the appropriate options function (setting this to the option).
In my opinion that is way overkill, but it seems to be what you are asking.
I guess a simpler version would be something like:
var optionFunctions = {
"1" : function() { ... },
"2" : function() { ... },
...
};
// code to create the options omitted
$("select").on("change", function() {
var fn = optionFunctions[$(this).val()];
if (fn)
fn.call(this.options[this.selectedIndex]);
});

Related

Jquery select2 - How to disable options in one dropdown without affecting all other dropdowns?

This is what I'm doing:
$('select').each(function () {
var selectedValue = $(this).find('option:selected').val();
if (selectedValue !== '0') {
$('option').each(function () {
if (!this.selected) {
$(this).attr('disabled', true);
}
});
}
});
The first option is "-Select an option-" that has a value of "0", that's why I do that validation. Basically what I want to do is to disable all options within a dropdown that has a selected value different than the first one. All dropdowns have been initialized with jquery's select2 and every one of them has a unique id.
The code I'm sharing doesn't work properly because I get the options disabled in every dropdown no matter if no option has been selected.
Can anybody help me fix this please?
I haven't tested but you should replace this line:
$('option').each(function () {
with this one:
$(this).find('option').each(function () {
Also, you should call this function using change event, which means i'ts triggered when some option is selected, like this:
$('select').on('change', function() {
The thing is that by doing this:
$('select').each(function () {
$('option').each(function () {
You were iterating through all select elements and all it's options, instead of iterating through the only select element that was clicked

select onchange event with parameter

I create n select in a cycle:
selCom = document.createElement("SELECT");
selCom.setAttribute("id", ("commessa"+n));
I would like to assign a function to each change: (for disable other select with same index)
selCom.setAttribute("onchange", "OnSelectionChange(this,n)");
with OnSelectionChange(this) works, OnSelectionChange(this,n) not work
function OnSelectionChange(select,indexDisable) {
var selectedOption = select.options[select.selectedIndex];
if ((selectedOption.value)=="Work"){
document.getElementById("Attivita"+indexDisable).disabled=true;
}else{
document.getElementById("Attivita"+indexDisable).disabled=false;
}
}
What is the correct form to use to also pass the parameter?
You can add event listener instead of setting the html attr like that.
function OnSelectionChange(indexDisable) {
var select = this;
var selectedOption = select.options[select.selectedIndex];
if ((selectedOption.value)=="Work"){
document.getElementById("Attivita"+indexDisable).disabled=true;
}else{
document.getElementById("Attivita"+indexDisable).disabled=false;
}
}
selCom.addEventListener('change', function(n){
OnSelectionChange(n);
}, false);
Other way is to use data-* attributes
<div data-id="1" onclick="dataTest()">TEST!</div>
Then in the JS function you could access id in the following way
function dataTest() {
alert(event.target.dataset.id);
}
here is more information about data-* attributes more info
And, here is the example

jquery select2 .on("change", function(e) reset option

i am using select2.
Usage : if a value is "COUNTRY", i want to add a onchange event to the select2, else i want to remove the onchange event as shown below :
var reportLevel = getReportLevel();
if (reportLevel != "COUNTRY") {
$("#selected_countries").on("change", function(e) {
prepareGlidModel(e);
});
} else {
$("#selected_countries").on("change", function(e) {
});
}
Issue : Not being able to remove the onchange event, even if the else block is called.
Events are called based upon the reportLevel value selected in a dropdown.
try following:
var reportLevel = getReportLevel(),
// by default unbind/off change event
$select = $("#selected_countries").off("change");
// and if country then bind it
if (reportLevel == "COUNTRY") {
$select.on("change", function(e) {
alert("you selected :" + $(this).val());
});
}
Working example here: http://jsfiddle.net/JB89B/1/
i think on else case you want to reset the value to default for this you have to use
$("#selected_countries").val('default value')
and if u just want to prevent the default action of onchange event than on else you can write
e.preventDefault()
this will help
You can use off to deatach event handlers from your elements as shown below:
$("#selected_countries").off('change');

How to know with jQuery that a "select" input value has been changed?

I know that there is the change event handling in jQuery associated with an input of type select. But I want to know if the user has selected another value in the select element ! So I don't want to run code when the user select a new element in the select but I want to know if the user has selected a different value !
In fact there are two select elements in my form and I want to launch an ajax only when the two select elements has been changed. So how to know that the two elements has been changed ?
You can specifically listen for a change event on your chosen element by setting up a binding in your Javascript file.
That only solves half your problem though. You want to know when a different element has been selected.
You could do this by creating a tracking variable that updates every time the event is fired.
To start with, give your tracking variable a value that'll never appear in the dropdown.
// Hugely contrived! Don't ship to production!
var trackSelect = "I am extremely unlikely to be present";
Then, you'll need to set up a function to handle the change event.
Something as simple as:-
var checkChange = function() {
// If current value different from last tracked value
if ( trackSelect != $('#yourDD').val() )
{
// Do work associated with an actual change!
}
// Record current value in tracking variable
trackSelect = $('#yourDD').val();
}
Finally, you'll need to wire the event up in document.ready.
$(document).ready(function () {
$('#yourDD').bind('change', function (e) { checkChange() });
});
First of all you may use select event handler (to set values for some flags). This is how it works:
$('#select').change(function () {
alert($(this).val());
});​
Demo: http://jsfiddle.net/dXmsD/
Or you may store the original value somewhere and then check it:
$(document).ready(function () {
var val = $('#select').val();
...
// in some event handler
if ($('#select').val() != val) ...
...
});
First you need to store previous value of the selected option, then you should check if new selected value is different than stored value.
Check out the sample!
$(document).ready(function() {
var lastValue, selectedValue;
$('#select').change(function() {
selectedValue = $(this).find(':selected').val();
if(selectedValue == lastValue) {
alert('the value is the same');
}
else {
alert('the value has changed');
lastValue = selectedValue;
}
});
});​
You can save the value on page load in some hidden field.
like
$(document).ready(function(){
$('hiddenFieldId').val($('selectBoxId').val());
then on change you can grab the value of select:
});
$('selectBoxId').change(function(){
var valChng = $(this).val();
// now match the value with hidden field
if(valChng == $('hiddenFieldId').val()){
}
});
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.change();
http://docs.jquery.com/Events/change

jQuery prevent change for select

I want to prevent a select box from being changed if a certain condition applies. Doing this doesn't seem to work:
$('#my_select').bind('change', function(ev) {
if(my_condition)
{
ev.preventDefault();
return false;
}
});
I'm guessing this is because by this point the selected option has already changed.
What are other ways of doing this?
Try this:
http://jsfiddle.net/qk2Pc/
var my_condition = true;
var lastSel = $("#my_select option:selected");
$("#my_select").change(function(){
if(my_condition)
{
lastSel.prop("selected", true);
}
});
$("#my_select").click(function(){
lastSel = $("#my_select option:selected");
});
In the event someone needs a generic version of mattsven's answer (as I did), here it is:
$('select').each(function() {
$(this).data('lastSelected', $(this).find('option:selected'));
});
$('select').change(function() {
if(my_condition) {
$(this).data('lastSelected').attr('selected', true);
}
});
$('select').click(function() {
$(this).data('lastSelected', $(this).find('option:selected'));
});
If you simply want to prevent interaction with the select altogether when my_condition is true, you could always just capture the mousedown event and do your event prevent there:
var my_condition = true;
$("#my_select").mousedown(function(e){
if(my_condition)
{
e.preventDefault();
alert("Because my_condition is true, you cannot make this change.");
}
});
This will prevent any change event from ever occurring while my_condition is true.
Another option to consider is disabling it when you do not want it to be able to be changed and enabling it:
//When select should be disabled:
{
$('#my_select').attr('disabled', 'disabled');
}
//When select should not be disabled
{
$('#my_select').removeAttr('disabled');
}
Update since your comment (if I understand the functionality you want):
$("#dropdown").change(function()
{
var answer = confirm("Are you sure you want to change your selection?")
{
if(answer)
{
//Update dropdown (Perform update logic)
}
else
{
//Allow Change (Do nothing - allow change)
}
}
});
Demo
None of the answers worked well for me. The easy solution in my case was:
$("#selectToNotAllow").focus(function(e) {
$("#someOtherTextfield").focus();
});
This accomplishes clicking or tabbing to the select drop down and simply moves the focus to a different field (a nearby text input that was set to readonly) when attempting to focus on the select. May sound like silly trickery, but very effective.
You can do this without jquery...
<select onchange="event.target.selectedIndex = 0">
...
</select>
or you can do a function to check your condition
<select onchange="check(event)">
...
</select>
<script>
function check(e){
if (my_condition){
event.target.selectedIndex = 0;
}
}
</script>
I was looking for "javascript prevent select change" on Google and this question comes at first result. At the end my solution was:
const $select = document.querySelector("#your_select_id");
let lastSelectedIndex = $select.selectedIndex;
// We save the last selected index on click
$select.addEventListener("click", function () {
lastSelectedIndex = $select.selectedIndex;
});
// And then, in the change, we select it if the user does not confirm
$select.addEventListener("change", function (e) {
if (!confirm("Some question or action")) {
$select.selectedIndex = lastSelectedIndex;
return;
}
// Here do whatever you want; the user has clicked "Yes" on the confirm
// ...
});
I hope it helps to someone who is looking for this and does not have jQuery :)
You might need to use the ".live" option in jQuery since the behavior will be evaluated in real-time based on the condition you've set.
$('#my_select').live('change', function(ev) {
if(my_condition)
{
ev.preventDefault();
return false;
}
});
Implement custom readonly like eventHandler
<select id='country' data-changeable=false>
<option selected value="INDIA">India</option>
<option value="USA">United States</option>
<option value="UK">United Kingdom</option>
</select>
<script>
var lastSelected = $("#country option:selected");
$("#country").on("change", function() {
if(!$(this).data(changeable)) {
lastSelected.attr("selected", true);
}
});
$("#country").on("click", function() {
lastSelected = $("#country option:selected");
});
</script>
Demo : https://jsfiddle.net/0mvajuay/8/
This was the ONLY thing that worked for me (on Chrome Version 54.0.2840.27):
$('select').each(function() {
$(this).data('lastSelectedIndex', this.selectedIndex);
});
$('select').click(function() {
$(this).data('lastSelectedIndex', this.selectedIndex);
});
$('select[class*="select-with-confirm"]').change(function() {
if (!confirm("Do you really want to change?")) {
this.selectedIndex = $(this).data('lastSelectedIndex');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='fruits' class="select-with-confirm">
<option selected value="apples">Apples</option>
<option value="bananas">Bananas</option>
<option value="melons">Melons</option>
</select>
<select id='people'>
<option selected value="john">John</option>
<option value="jack">Jack</option>
<option value="jane">Jane</option>
</select>
This worked for me, no need to keep a lastSelected if you know the optionIndex to select.
var optionIndex = ...
$(this)[0].options[optionIndex].selected = true;
$('#my_select').bind('mousedown', function (event) {
event.preventDefault();
event.stopImmediatePropagation();
});
if anybody still interested, this solved the problem, using jQuery 3.3.1
jQuery('.class').each(function(i,v){
jQuery(v).data('lastSelected', jQuery(v).find('option:selected').val());
jQuery(v).on('change', function(){
if(!confirm('Are you sure?'))
{
var self = jQuery(this);
jQuery(this).find('option').each(function(key, value){
if(parseInt(jQuery(value).val()) === parseInt(self.data('lastSelected')))
{
jQuery(this).prop('selected', 'selected');
}
});
}
jQuery(v).data('lastSelected', jQuery(v).find('option:selected').val());
});
});
None of the other answers worked for me, here is what eventually did.
I had to track the previous selected value of the select element and store it in the data-* attribute. Then I had to use the val() method for the select box that JQuery provides. Also, I had to make sure I was using the value attribute in my options when I populated the select box.
<body>
<select id="sel">
<option value="Apple">Apple</option> <!-- Must use the value attribute on the options in order for this to work. -->
<option value="Bannana">Bannana</option>
<option value="Cherry">Cherry</option>
</select>
</body>
<script src="https://code.jquery.com/jquery-3.5.1.js" type="text/javascript" language="javascript"></script>
<script>
$(document).ready()
{
//
// Register the necessary events.
$("#sel").on("click", sel_TrackLastChange);
$("#sel").on("keydown", sel_TrackLastChange);
$("#sel").on("change", sel_Change);
$("#sel").data("lastSelected", $("#sel").val());
}
//
// Track the previously selected value when the user either clicks on or uses the keyboard to change
// the option in the select box. Store it in the select box's data-* attribute.
function sel_TrackLastChange()
{
$("#sel").data("lastSelected", $("#sel").val());
}
//
// When the option changes on the select box, ask the user if they want to change it.
function sel_Change()
{
if(!confirm("Are you sure?"))
{
//
// If the user does not want to change the selection then use JQuery's .val() method to change
// the selection back to what it was previously.
$("#sel").val($("#sel").data("lastSelected"));
}
}
</script>
I hope this can help someone else who has the same problem as I did.

Categories

Resources