I have constructed a dynamic select using jQuery like below:
Based on YesOrNo, I have to show/hide options in Source and Type
Yes/No Source Type
---------------------------------------------
Yes Yes1 and Yes2 Yes
No No1 and No2 No1 to 6
HTML:
<select id="YesOrNo" name='YesOrNo'>
<option value=''>Select Yes/No</option>
<option value='1'>Yes</option>
<option value='2'>No</option>
</select>
<select id='Source' name='Source'>
<option value=''>Select Source</option>
<option data-aob='Yes' value='1'>Yes1</option>
<option data-aob='Yes' value='2'>Yes2</option>
<option data-aob='No' value='3'>No1</option>
<option data-aob='No' value='4'>No2</option>
</select>
<select id="Type" name='Type'>
<option value=''>Select Type</option>
<option data-aob='No' value='1'>No1</option>
<option data-aob='No' value='2'>No2</option>
<option data-aob='No' value='3'>No3</option>
<option data-aob='No' value='4'>No4</option>
<option data-aob='Yes' value='5'>Yes</option>
<option data-aob='No' value='6'>No5</option>
<option data-aob='No' value='7'>No6</option>
</select>
JQuery:
$('#YesOrNo').on('change', function () {
if (this.value === '1') {
$('#Source option[data-aob=Yes]').show();
$('#Source option[data-aob=No]').hide();
$('#Type option[data-aob=Yes]').show();
$('#Type option[data-aob=No]').hide();
$("#Source option:selected").prop("selected", false);
$("#Type option:selected").prop("selected", false);
} else if (this.value === "2") {
$('#Source option[data-aob=Yes]').hide();
$('#Source option[data-aob=No]').show();
$('#Type option[data-aob=Yes]').hide();
$('#Type option[data-aob=No]').show();
$("#Source option:selected").prop("selected", false);
$("#Type option:selected").prop("selected", false);
} else {
$('#Source option').show();
$('#Type option').show();
$("#Source option:selected").prop("selected", false);
$("#Type option:selected").prop("selected", false);
}
});
Here is my JSFiddle
This is working perfect as I expected. Since the values are obtained from database, I have a problem while displaying the selected option in YesOrNo.
<select id="YesOrNo" name='YesOrNo'>
<option value=''>Select Yes/No</option>
<option selected value='1'>Yes</option>
<option value='2'>No</option>
</select>
Here the option "Yes" is selected by default, but here http://jsfiddle.net/ubVfa/1/ still showing the four options and Type showing all 7 options.
Yes/No Source Type
--------------------------------------------------------------------
Yes(SELECTED by default) All 4 options All 7 Options
How to tune my code to update the options in select dynamically.
Any help is appreciated.
You can call $("...").change() after the page is loaded:
$(function(){
$('#YesOrNo').change();
});
See my fiddle:
I also hid the options when nothing is selected, calling $("...").hide() in the "onchange" event handler.
The $(func) with func as an anonymous function is a syntatic suggar for $(document).ready(func), which calls that given function after loading.
The "change" call is just a trigger call, like $("...").trigger("change").
You can use trigger to manually invoke the handler on page load.... still your solution will not work in IE... see further changes below
var sourceHtml = $('#Source').html();
var typeHtml = $('#Type').html();
$('#YesOrNo').on('change', function () {
var sources = $(sourceHtml);
var types = $(typeHtml);
var aob = $(this).find('option:selected').data('aob');
if(aob){
sources = sources.filter('[data-aob="' + aob + '"]');
types = types.filter('[data-aob="' + aob + '"]');
}
$('#Source').empty().append(sources)
$('#Type').empty().append(types)
}).triggerHandler('change');
Demo: Fiddle
You can simply do this by triggering change event on load.
just add below code inside document.ready
$('#YesOrNo').trigger('change');
and for test it add selected="selected" for No option and run the code.
See Demo
If your code logic allows this trigger a change event once.
//Triggering a change event on document ready
$(document).ready(function(){
$('#YesOrNo').trigger('change');
});
JS FIDDLE
Related
given:
<select id="mySelect">
<option>..</option>
...
</select>
Using the select id, how can I trigger a click event on one of the options? I tried attaching the event directly to the select, but this triggers an event whenever the select is clicked on (even if there are no options). Oh, and it is a multi-select (although I don't think that matter).
You want the 'change' event handler, instead of 'click'.
$('#mySelect').change(function(){
var value = $(this).val();
});
$('#mySelect').on('change', function() {
var value = $(this).val();
alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<select id="mySelect">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
<option value='8'>8</option>
</select>
EXAMPLE
you can attach a focus event to select
$('#select_id').focus(function() {
console.log('Handler for .focus() called.');
});
The problem that I had with the change handler was that it triggered on every keypress that I scrolled up and down the <select>.
I wanted to get the event for whenever an option was clicked or when enter was pressed on the desired option. This is how I ended up doing it:
let blockChange = false;
$element.keydown(function (e) {
const keycode = (e.keyCode ? e.keyCode : e.which);
// prevents select opening when enter is pressed
if (keycode === 13) {
e.preventDefault();
}
// lets the change event know that these keypresses are to be ignored
if([38, 40].indexOf(keycode) > -1){
blockChange = true;
}
});
$element.keyup(function(e) {
const keycode = (e.keyCode ? e.keyCode : e.which);
// handle enter press
if(keycode === 13) {
doSomething();
}
});
$element.change(function(e) {
// this effective handles the click only as preventDefault was used on enter
if(!blockChange) {
doSomething();
}
blockChange = false;
});
You can also try this to get previous value of select and the clicked value.
HTML
<select name="status">
<option value="confirmed">confirmed</option>
<option value="packed">packed</option>
<option value="shiped">shiped</option>
<option value="delivered">delivered</option>
</select>
script
var previous;
$("select[name=status]").focus(function () {
previous = this.value;
}).change(function() {
var next = $(this).val()
alert("previous: "+previous+ " and Next: "+ next)
previous = this.value;
});
<select name="data" id = 'cohort' class="form-control" style = "width:215px; margin-left:20px; margin-bottom:8px ; height:30px" >
<option value = 0>All</option>
<option value = 1>Diseases</option>
<option value = 2>Drugs</option>
<option value = 3>Procedures</option>
</select>
const element = document.getElementById("cohort");
const event = new MouseEvent("mousedown");
element.dispatchEvent(event);
What I have done in this situation is that I put in the option elements OnClick event like this:
<option onClick="something();">Option Name</option>
Then just create a script function like this:
function something(){
alert("Hello");
}
UPDATE:
Unfortunately I can't comment so I'm updating here
TrueBlueAussie apparently jsfiddle is having some issues, check here if it works or not: http://js.do/code/klm
its working for me
<select name="" id="select">
<option value="1"></option>
<option value="2"></option>
<option value="3"></option>
</select>
<script>
$("#select > option").on("click", function () {
alert(1)
})
</script>
One possible solution is to add a class to every option
<select name="export_type" id="export_type">
<option class="export_option" value="pdf">PDF</option>
<option class="export_option" value="xlsx">Excel</option>
<option class="export_option" value="docx">DocX</option>
</select>
and then use the click handler for this class
$(document).ready(function () {
$(".export_option").click(function (e) {
//alert('click');
});
});
UPDATE: it looks like the code works in FF, IE and Opera but not in Chrome.
Looking at the specs http://www.w3.org/TR/html401/interact/forms.html#h-17.6 I would say it's a bug in Chrome.
I have two dropdowns, and I want it so that, when the user changes the first dropdown, the second gets updated automatically to the same value. Due to some complicated reasons, I have to trigger the change via an on() delegate event. My code is like this:
<form>
<select id="destino_1">
<option value="268">AAA</option>
<option value="409">BBB</option>
<option value="570">CCC</option>
<option value="895">DDD</option>
<option value="943">Arena</option>
</select>
<select id="origen_2" class="origen">
<option value="268">AAA</option>
<option value="409">BBB</option>
<option value="570">CCC</option>
<option value="895">DDD</option>
<option value="943">Arena</option>
</select>
</form>
And my Javascript is this:
$("body").on('change',"#destino_1", function(){
$("#origen_2").trigger("cambiaOrigen");
});
$('body').on('cambiaOrigen', '.origen', function() {
var nombre=this.id;
var numero=parseInt(nombre.slice(-1));
//alert("Mooooo " + nombre);
if (numero > 1) {
var anterior = $("#destino_" + (numero - 1)).val();
this.find("option[value='" + anterior + "']").prop("selected", "selected").change();
//this.val(anterior);
}
});
I've created a fiddle at http://jsfiddle.net/w7c4o4cd/
As you can see, the event gets correctly triggered, the code gets the value of the first dropdown... but then I can't change the value of the second dropdown. I've tried both ways: with
this.find("option[value='" + anterior + "']").prop("selected", "selected").change();
And also with this.val(anterior);. Neither of them work. When executing in a browser, the error I get in the console is that this.find and this.val() are not functions... and yet, if you try to display this.id, it seems that this is referring correctly to the second dropdown, instead of to, say, body. (Also, if I try to display this, it says that it's an "HTML selectElement").
What's going on?
In your cambiaOrigen handler, this refers to a node not a jQuery object, what you would want is $(this) instead.
Also to set the selected option of a select tag you can simply set its value
this.value = anterior;
http://jsfiddle.net/mowglisanu/w7c4o4cd/2/
$("body").on('change',"#destino_1", function(){ $("#origen_2").trigger("cambiaOrigen");
});
$('body').on('cambiaOrigen', '.origen', function() {
var nombre=this.id;
var numero=parseInt(nombre.slice(-1));
//alert("Mooooo " + nombre);
if (numero > 1) {
var anterior = $("#destino_" + (numero - 1)).val();
//alert("Meeeept " + anterior);
//alert (this);
this.value = anterior;
//this.val(anterior);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form>
<select id="destino_1">
<option value="268">AAA</option><option value="409">BBB</option><option value="570">CCC</option><option value="895">DDD</option><option value="943">Arena</option>
</select>
<select id="origen_2" class="origen">
<option value="268">AAA</option><option value="409">BBB</option><option value="570">CCC</option><option value="895">DDD</option><option value="943">Arena</option>
</select>
</form>
Just change this line
this.find("option[value='" + anterior + "']").prop("selected", "selected").change();
to this
$(this).find("option[value='" + anterior + "']").prop("selected", "selected").change();
Just set the value of the section dropdown based on the value of the first like this.
$("body").on('change', "#destino_1", function () {
$('#origen_2').val($(this).val());
});
$("body").on('change', "#destino_1", function () {
$('#origen_2').val($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="destino_1">
<option value="268">AAA</option>
<option value="409">BBB</option>
<option value="570">CCC</option>
<option value="895">DDD</option>
<option value="943">Arena</option>
</select>
<select id="origen_2" class="origen">
<option value="268">AAA</option>
<option value="409">BBB</option>
<option value="570">CCC</option>
<option value="895">DDD</option>
<option value="943">Arena</option>
</select>
</form>
Question
I want to disable a single option with JS. I tried using the following code:
var input = $('input[value="' + selectedPriLang + "Sec" + '"]');
input.prop('disabled', false);
input.parent('li').addClass('disabled');
It kind of works, but the problem is I can still enable the option using the Select all button.
Also, not sure if relevant, I execute the code in a onChange from a different multiselect.
<select id="sel_secLang" multiple="multiple">
<option value="nlSec" disabled="disabled">Dutch</option>
<option value="enSec">English</option>
<option value="deSec">German</option>
<option value="FrSec">French</option>
</select>
Hope this explanation is clear enough, first question ;D.
Answer
Although Joe's answer worked I tried it out myself, For disabling:
var input = $('input[value="' + selectedPriLang + "Sec" + '"]');
input.prop('disabled', true);
var input2 = input.parent('label').parent('a').parent('li');
input4.removeClass('active');
input4.addClass('disabled');
For enabling:
var input = $('input[value="' + selectedPriLang + "Sec" + '"]');
input.prop('disabled', false);
var input2 = input.parent('label').parent('a').parent('li');
input2.removeClass('disabled');
Just the value of the input
selectedPriLang = $('#sel_priLang option:selected').val();
Just a quick note to clarify: disabling the corresponding checkbox and adding the .disabled class to the appropriate li is not sufficient. You also have to disable the underlying option. Example (can also be found in the documentation):
<script type="text/javascript">
$(document).ready(function() {
$('#example-disable-javascript').multiselect({
includeSelectAllOption: true
});
$('#example-disable-javascript-disable').on('click', function() {
var input = $('#example-disable-javascript-container input[value="3"]');
var option = $('#example-disable-javascript-container option[value="3"]');
input.prop('disabled', true);
option.prop('disabled', true);
input.parent('label').parent('a').parent('li').addClass('disabled');
});
$('#example-disable-javascript-check').on('click', function() {
var options = '';
$('#example-disable-javascript option:selected').each(function() {
options += $(this).val() + ', ';
});
alert(options.substr(0, options.length - 2));
});
});
</script>
<div class="btn-group" id="example-disable-javascript-container">
<select id="example-disable-javascript" multiple="multiple">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
<option value="5">Option 5</option>
<option value="6">Option 6</option>
</select>
<button id="example-disable-javascript-disable" class="btn btn-primary">Disable an option!</button>
<button id="example-disable-javascript-check" class="btn btn-primary">Check</button>
</div>
You'll have to process the disabled events in an on-change handler on you're own and de-select them when the select-all is picked. Generally the process could look like:
Capture on selection event for select all
Iterate on elements
Remove the checked attribute for the disabled elements
Something along the lines of capturing on change, find disabled, and unchecking them:
$('#sel_secLang').multiselect({
onChange: function(option, checked, select) {
$('input[type=checkbox]:disabled').each(checkbox, function(){
checkbox.attr('checked', false);
});
}
});
I have searching the web for a while and still I cant find an answer, I have three drop-down menus on my site.
I use them for accepting user preferences so the user can control the output of results.
So I want to know if its possible for the value to be taken out of the other 2 dropdowns if its selected in one.
for example if the user selects movies in the first one it wont be in the others.
here is my dropdowns
<select id="pref1select">
<option value="P">Preference One</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
<select id="pref2select">
<option value="P">Preference Two</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
<select id="pref3select">
<option value="P">Preference Three</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
This will disable it, but not remove it.
Fiddle: http://jsfiddle.net/p2SFA/1/
HTML: (Added .preferenceSelect class) and jQuery:
$(document).ready(function() {
$(".preferenceSelect").change(function() {
// Get the selected value
var selected = $("option:selected", $(this)).val();
// Get the ID of this element
var thisID = $(this).prop("id");
// Reset so all values are showing:
$(".preferenceSelect option").each(function() {
$(this).prop("disabled", false);
});
$(".preferenceSelect").each(function() {
if ($(this).prop("id") != thisID) {
$("option[value='" + selected + "']", $(this)).prop("disabled", true);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<select id="pref1select" class="preferenceSelect">
<option value="P">Preference One</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
<select id="pref2select" class="preferenceSelect">
<option value="P">Preference Two</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
<select id="pref3select" class="preferenceSelect">
<option value="P">Preference Three</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
If you want it removed, you will probably have to make jQuery know what to insert when it has reset because a new choice is made :)
This should work for you:
$(document).ready(function() {
$(".preferenceSelect").change(function() {
// Get the selected value
var selected = $("option:selected", $(this)).val();
// Get the ID of this element
var thisID = $(this).attr("id");
// Reset so all values are showing:
$(".preferenceSelect option").each(function() {
$(this).show();
});
$(".preferenceSelect").each(function() {
if ($(this).attr("id") != thisID) {
$("option[value='" + selected + "']", $(this)).hide();
}
});
});
});`
You should try this:
$(".preferenceSelect").on("change", function () {
$(".preferenceSelect option").prop("disabled", false);
var selectPref = $("option:selected", $(this)).val();
var selectId = $(this).prop("id");
$(".preferenceSelect option").each(function () {
$(this).show();
});
$(".preferenceSelect").each(function () {
if ($(this).prop("id") != selectId) {
$("option[value='" + selectPref + "']", $(this)).prop("disabled", true);
}
});
});
This must be work for you.
I believe something like this would do the trick given the HTML above:
var $selects = $("select");
$selects.on("change", function(){
var value = this.value;
$("option[value='" + value +"']", $selects).prop("disabled", true);
});
var $selects = $("select");
$selects.on("change", function(){
var value = this.value;
$("option[value='" + value +"']", $selects).prop("disabled", true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="pref1select">
<option value="P">Preference One</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
<select id="pref2select">
<option value="P">Preference Two</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
<select id="pref3select">
<option value="P">Preference Three</option>
<option value="M">Movie</option>
<option value="T">Tv</option>
<option value="G">Games</option>
</select>
This disables the duplicate options, but it's an easy change to remove them as well. You'll run into a slight issue, though, since the "Preference #" options all have the same value. I would recommend either making these optgroup labels or removing the values entirely and marking them as disabled from the start...since you shouldn't be able to click them in the first place. You can find a bit more on option labels, and separators answered here.
Example
Please try the following which is working fine with no issue. I am also marking the selected option as disable instead of hiding from the other dropdowns.
$( function() {
courC();
});
function courC(){
var previous;
$(".pSel").on('focus', function () {
previous = this.value;
}).change(function() {
var selected = $("option:selected", $(this)).val();
var thisID = $(this).attr("id");
$(".pSel option").each(function() {
$(this).show();
});
$(".pSel").each(function() {
var otid=$(this).attr("id");
if (otid != thisID) {
if( $('#'+otid).val() == selected){ $('#'+otid).val(''); } // this is required when you are viewing data once again after the form submission
$("option[value='" + selected + "']", $(this)).attr("disabled", true);
}
$("option[value='" + previous + "']", $(this) ).attr("disabled", false); // this will help to reset the previously selected option from all dropdown
});
previous = $('#'+thisID).val();
});
}
given:
<select id="mySelect">
<option>..</option>
...
</select>
Using the select id, how can I trigger a click event on one of the options? I tried attaching the event directly to the select, but this triggers an event whenever the select is clicked on (even if there are no options). Oh, and it is a multi-select (although I don't think that matter).
You want the 'change' event handler, instead of 'click'.
$('#mySelect').change(function(){
var value = $(this).val();
});
$('#mySelect').on('change', function() {
var value = $(this).val();
alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<select id="mySelect">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
<option value='8'>8</option>
</select>
EXAMPLE
you can attach a focus event to select
$('#select_id').focus(function() {
console.log('Handler for .focus() called.');
});
The problem that I had with the change handler was that it triggered on every keypress that I scrolled up and down the <select>.
I wanted to get the event for whenever an option was clicked or when enter was pressed on the desired option. This is how I ended up doing it:
let blockChange = false;
$element.keydown(function (e) {
const keycode = (e.keyCode ? e.keyCode : e.which);
// prevents select opening when enter is pressed
if (keycode === 13) {
e.preventDefault();
}
// lets the change event know that these keypresses are to be ignored
if([38, 40].indexOf(keycode) > -1){
blockChange = true;
}
});
$element.keyup(function(e) {
const keycode = (e.keyCode ? e.keyCode : e.which);
// handle enter press
if(keycode === 13) {
doSomething();
}
});
$element.change(function(e) {
// this effective handles the click only as preventDefault was used on enter
if(!blockChange) {
doSomething();
}
blockChange = false;
});
You can also try this to get previous value of select and the clicked value.
HTML
<select name="status">
<option value="confirmed">confirmed</option>
<option value="packed">packed</option>
<option value="shiped">shiped</option>
<option value="delivered">delivered</option>
</select>
script
var previous;
$("select[name=status]").focus(function () {
previous = this.value;
}).change(function() {
var next = $(this).val()
alert("previous: "+previous+ " and Next: "+ next)
previous = this.value;
});
<select name="data" id = 'cohort' class="form-control" style = "width:215px; margin-left:20px; margin-bottom:8px ; height:30px" >
<option value = 0>All</option>
<option value = 1>Diseases</option>
<option value = 2>Drugs</option>
<option value = 3>Procedures</option>
</select>
const element = document.getElementById("cohort");
const event = new MouseEvent("mousedown");
element.dispatchEvent(event);
What I have done in this situation is that I put in the option elements OnClick event like this:
<option onClick="something();">Option Name</option>
Then just create a script function like this:
function something(){
alert("Hello");
}
UPDATE:
Unfortunately I can't comment so I'm updating here
TrueBlueAussie apparently jsfiddle is having some issues, check here if it works or not: http://js.do/code/klm
its working for me
<select name="" id="select">
<option value="1"></option>
<option value="2"></option>
<option value="3"></option>
</select>
<script>
$("#select > option").on("click", function () {
alert(1)
})
</script>
One possible solution is to add a class to every option
<select name="export_type" id="export_type">
<option class="export_option" value="pdf">PDF</option>
<option class="export_option" value="xlsx">Excel</option>
<option class="export_option" value="docx">DocX</option>
</select>
and then use the click handler for this class
$(document).ready(function () {
$(".export_option").click(function (e) {
//alert('click');
});
});
UPDATE: it looks like the code works in FF, IE and Opera but not in Chrome.
Looking at the specs http://www.w3.org/TR/html401/interact/forms.html#h-17.6 I would say it's a bug in Chrome.