Jquery: change value of a dropdown... when triggered through a delegate event - javascript

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>

Related

Trigger a javascript function after select multiple option from <select> tag

I have a multi select tag is here. I like to call a function after select multiple option from select tag.
<select name="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
If any body mark as duplicate please let me know the correct link. I search lots here and google also. but non of solution is good for my problem.
You can listen to change event in the same way as you do this with non-multiple select:
$("#cars").on('change', function()
{
var selectedItems = $(this).find("option:selected");
if (selectedItems.length <= 1)
{
$("#result").text("not multiple!");
return;
}
var text = "";
$.each(selectedItems, function() {
text += $(this).val() + " ";
});
$("#result").text(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="cars" name="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<div id="result"></div>
Use .change instead like so :
$('select').change(function(e){
var length = $('option:selected', this).length;
if ( length > 1 ) {
alert('hey');
}
});
DEMO
You can do something like this with help of change() and blur() event handler
$('select').change(function() {
if ($('option:selected', this).length > 1) {
// set custom data attribute value as 1 when change event occurred and selected options are greater than 1
$(this).data('select', 1);
} else
//set value as zero in other case
$(this).data('select', 0);
}).blur(function() {
if ($(this).data('select')) {
// when focus out check custom attribute value
alert('selected more than one');
// code here
// call your function here
}
$(this).data('select', 0)
// set custom attribute value to 0
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
try this, it will call a function passing the newly selected value into functionToCall.
var values = [];
$('select').change(function(e){
var current = $(this).find('option:selected').map(function() {
return $(this).val();
});
var newValue = $(current).not(values).get();
values = current;
if(newValue.length)
functionToCall(newValue);
});
function functionToCall(value){
alert(value);
console.log(value);
}
Fiddle

Disable a specific option boostrap-multiselect

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);
});
}
});

How to get the value of the first HTML option by default in jQuery?

I'm using jQuery 1.9.1 and jQuery Mobile 1.3.1, and I have HTML like this:
<p>
How many days did your menstrual cycle last?
<select id="menstrualCycle" onclick="changeFunc('menstrualCycle')">
<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>
</select>
</p>
Then I have a JS like this:
function changeFunc(select) {
var selectBox = document.getElementById(select);
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
if (select == 'monthCycle') {
monthDays = selectedValue;
console.log("Month value is: " + monthDays);
} else if (select == 'menstrualCycle') {
menstrualDays = selectedValue;
console.log("Menstrual value is: " + menstrualDays);
} else if (select == 'lutealPhase') {
lutealValue = selectedValue;
console.log("Luteal value is: " + lutealValue);
}
}
The point is that I get the values, by clicking the options or selecting other options. But when the page is open, where my page id is "ovulInfoPicker", by defualt it doesn't get the first values. I want to get the first values by default, without changing the values or pressing the otions.
Trigger the change event programmatically: http://api.jquery.com/trigger.
$('#id1, #id2, #id3').trigger('change');
You trigger the event which will execute the event handlers without actual user interaction.
<option value="3" selected="selected">3</option>

Remove a dropdown value that has been selected from another dropdown menu

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();
});
}

Update options in select dynamically

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

Categories