change selected option of dropDown using jQuery - javascript

I have a dropdown on change a popup appears with a warning that change the value will do some affects. when user select no the dropdown selected index is supposed to return to initial selected option. here is what I do:
function closeDeleteVariantsPopup(){
parent.$.fn.colorbox.close();
var elementSpecies= parent.document.getElementsByClassName("speice");
for(var i = 0;i<elementSpecies[0].options.length; ++i) {
alert(parent.document.getElementById("speciesHiddenValue").value);
if(elementSpecies[0].options[i].id === parent.document.getElementById("speciesHiddenValue").value) {
alert(parent.document.getElementById("speciesHiddenValue").value);
elementSpecies[0].selectedIndex = i;
break;
}
}
}
html & freemarker:
[#spring.bind "genomicReferenceBean.specie.id"/]
<select name="specie.id" id="specie.id" [#if !(genomicReferenceBean.specie?has_content) || genomicReferenceBean.specie.id==-1] multiple="multiple" [/#if] class='speice singleList' onchange='getMaterials()' >
[#if genomicReferenceInitializerBean.species?has_content]
[#list genomicReferenceInitializerBean.species as initializerValueBean]
<option for="selectSpecie" name="${initializerValueBean.name}" [#if genomicReferenceBean.specie?has_content && genomicReferenceBean.specie.id?number == initializerValueBean.id] selected="selected" [/#if] value="${initializerValueBean.id}">${initializerValueBean.name}</option>
[/#list]
[/#if]
</select>
<input type="hidden" id="speciesHiddenValue" value="${genomicReferenceBean.specie.id?number}"/>
now when I press no button the popup close and nothing happen

I used jQuery and it worked fine:
parent.$(".speice option").each(function(){
if($(this).val() === parent.document.getElementById("speciesHiddenValue").value) {
$(this).attr('selected', 'selected');
}
});

Related

Moving option value on top of dropdown list using jQuery

I have this code:
function SelectReferralFromQueryString() {
var queryStringName = GetParameterValues('Referral');
if (queryStringName != undefined || queryStringName != null) {
queryStringName = decodeURIComponent(queryStringName);
var exists = false;
$('#refDropDown option').each(function () {
if (this.value == queryStringName) {
exists = true;
var option = $(this);
$(this).remove();
$('#refDropDown option').prepend(option);
return false;
}
});
if (exists == true){
DropDownReferral.value = queryStringName;
$("#refDropDown").prop("disabled", true);
}
}
}
function GetParameterValues(param) {
var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < url.length; i++) {
var urlparam = url[i].split('=');
if (urlparam[0] == param) {
return urlparam[1];
}
else
return false;
}
}
And this HTML:
<select name="refDropDown" id="refDropDown" class="items" data-hidden-field="DropDownReferral">
<option value="">Please Select</option>
<option value="Albert">Al</option>
<option value="Steve T">Steve</option>
</select>
So, the logic is:
If 'Referral' which is a query string, gets passed, then I am checking the value in my select option and moving it on top and disabling the dropdown. NOT WORKING! See the picture below.
If the dropdown doesnt have the query string value then disable the dropdown and store it in the hidden field. (WORKING!)
What I am missing here?
If I am passing ?Referral=Albert, then it should show me 'Al' on top. If I am passing ?Referral=Steve, then is show 'Steve' on top and disable the dropdown.
You can use the val() function of jQuery to select the option:
$("#refDropDown").val(queryStringName);
If you can count on the referral being a valid value you can try this (untested):
$('#refDropDown').val(queryStringName).prop('disabled', true);
Otherwise check for whether or not the value exists first by doing something like this:
if($('#refDropDown option[value="' + queryStringName + '"]').length != 0){
//code above here
}
Then get rid of that loop over the options and that if that is setting the select box to disabled.
Also as a side note, a disabled select box won't submit a value when you submit the form, so you will need to use the referral parameter, or a hidden field.

How to get all different dropdown have selected value or not

I want to check that all dropdown on page have select value or not?
fox Ex:-
<select id="#model.Id">
<option value="0">---</option>
<option value="1">abc</option>
<option value="2">xyz</option>
</select>
<select id="#model.Id">
<option value="0">---</option>
<option value="14">abc</option>
<option value="25">xyz</option>
</select>
Both are not same page and and issue there is dynamic id and name are assign to both of dropdrop down so i can't use jQuery by id or name and get selected value, not i want to check that both have selected value by Javascript or jQuery?
How can I do this?
Regards,
Vinit
Try this : you can iterate all select boxes on page using .each() and compare it's value with 0. If select value is 0 it means it is not selected otherwise selected.
$(function(){
$('select').each(function(){
var value = $(this).val();
var id = $(this).attr('id');
if(value==0)
alert('this dropdown has no selected value, id = '+id);
else
alert('this dropdown has selected value, id = '+id);
}):
});
Edit - as OP want to check if both dropdowns selected then show button otherwise hide it, use below code
$(function(){
$('select').change(function(){
var totalUnselectedDropdown = $('select option[value="0"]:selected').length;
if(totalUnselectedDropdown==0)
{
// enable button
$('#buttonId').prop('disabled',false);
}
else
{
// disable button
$('#buttonId').prop('disabled',true);
}
}):
});
you can do it this way:
$("select").each(function(){
alert($(this).val()) // will alert selected option value attribute value
if($(this).val() > 0) // value greater than 0 means value selected
{
alert("Value Selected")
}
})
Try this :
$("select").each(function(){
if(parseInt($(this).val()) > 0){
//all select have selected value
}
else
{
//any one/all select have not selected value
return false;
}
});

How to remove an option from a select element with Select2 applied?

So, I have this HTML code:
<input type="checkbox" id="orders_lives_in_ccs" name="orders[lives_in_ccs]" class="lives_in_ccs">
<select id="orders_shipping_from" name="orders[shipping_from]" required="required" class="shipping_from toSelect2">
<option value="" selected="selected">-- SELECCIONAR --</option>
<option value="MRW">MRW - COBRO EN DESTINO</option>
<option value="DOMESA">DOMESA - COBRO EN DESTINO</option>
<option value="ZOOM">GRUPO ZOOM - COBRO EN DESTINO</option>
</select>
I need to remove the option MRW when checkbox .lives_in_ccs is checked so I made this code:
$(function () {
$('.toSelect2').select2();
var detachedMember;
$('.lives_in_ccs').click(function () {
if (this.checked) {
detachedMember = $('.shipping_from option[value="MRW"]').detach();
} else {
$('.shipping_from option[value=""]').after(detachedMember);
}
$(".secure_shipping").toggle(this.checked);
});
});
This code works but I'm having a problem and didn't found the way to fixit. Having this jsFiddle do this tests:
Leave the SELECT with the default value which is --SELECCIONAR-- and mark the check in the left side, that will works and will remove the option MRW from the main SELECT, if you unmark the check the value will appear again on the SELECT
Choose MRW (the first choice) on the SELECT and mark the check in the left side, that will remove the option MRW from the main SELECT, but will leave the option as SELECTED which is wrong since the server side isn't expecting it.
So, how do I remove the option even if it's selected on the SELECT element? Any help?
Here is the updated fiddle for testing: http://jsfiddle.net/fgaqgpd7/2/
This will reset the value of the select2 input:
$('.toSelect2').select2('val','');
You can apply it you click event handler. Basically if MRW is selected, then reset the select2 value.
$(function () {
$('.toSelect2').select2();
var detachedMember;
$('.lives_in_ccs').click(function () {
if (this.checked) {
if ($('.toSelect2').select2('val') == 'MRW') {
$('.toSelect2').select2('val','');
}
detachedMember = $('.shipping_from option[value="MRW"]').detach();
} else {
$('.shipping_from option[value=""]').after(detachedMember);
}
$(".secure_shipping").toggle(this.checked);
});
});
try this :
if($(".lives_in_ccs").is(':checked')){
$("#orders_shipping_from option[value='MRW']").remove();
}
Hope this helps :)
For me in version Select2 4.0.13:
$('#my-form').on('change', '.checkbox-item', updateDropdown);
HTML object:
<input type="checkbox" name="checkbox_1" id="checkbox_1" value="1" class="form-control checkbox-item" data-text="Label" />
Event function:
function updateDropdown(e) {
if (e.target.checked) {
if ($('#dropdown').select2('val') == $(this).val()) {
$('#dropdown').select2('val', '');
} else {
var newOption = new Option($(this).attr('data-text'), $(this).val(), false, false);
$('#dropdown').append(newOption).trigger('change');
}
} else {
$('#dropdown option[value="' + $(this).val() + '"]').detach();
}
}

Disable select option in group of select dropdowns when option is selected

What I'm trying to do: I have multiple select dropdowns, if an option is selected in one of the select dropdowns and the value exists in any of the other dropdowns the value should be disabled/unselectable, it again can become enabled/selectable if the selection is changed.
What happens with current code: it works about 50%, I can't pinpoint the issue, but I think because I'm applying a for loop some values get skipped and not disabled and sometimes the "Select" default option becomes disabled?!
Approach: The way I wrote my code was when a selection from the dropdown box occurs, enable all options, get the first dropdown's current selected value, if it's not the default "Select" then go through every dropdown box and disable any matching values, then repeat this process for the second dropdown's current selected value and so on.
Fiddle: http://jsfiddle.net/haakym/r2y73ndt/
Code:
HTML:
<div id="nomineeInfo">
<div>
<label>Manager</label>
<select class="positionTypes" id="pos_manager">
<option value="0">Select</option>
<option value="1">John Smith</option>
<option value="2">Jane Smith</option>
<option value="4">John Smoe</option>
</select>
</div>
<div>
<label>Deputy</label>
<select class="positionTypes" id="pos_deputy_manager">
<option value="0">Select</option>
<option value="1">John Smith</option>
<option value="2">Jane Smith</option>
<option value="3">John Doe</option>
</select>
</div>
<div>
<label>Finance</label>
<select class="positionTypes" id="pos_finance">
<option value="0">Select</option>
<option value="1">John Smith</option>
<option value="3">John Doe</option>
<option value="4">John Smoe</option>
</select>
</div>
Javascript:
$('#nomineeInfo').on('change', '.positionTypes', function () {
var selectedValue = $(this).val();
var dropdownOnChangeId = $(this).prop('id');
var positionTypesEn = ['manager', 'deputy_manager', 'finance'];
// set all enabled
for (var i = 0; i < 7; i++) {
$('#pos_'+positionTypesEn[i]).each(function(){
$("option", this).removeAttr('disabled');
});
};
for (var i = 0; i < 7; i++) {
// if position type selected value is not 0, i.e. if it's not "Select"
if( $('#pos_' + positionTypesEn[i]).val() != 0 ){
// go through each option in every dropdown
for (var j = 0; j < 7; j++) {
console.log( positionTypesEn[j] ); // show current dropdown
$('#pos_' + positionTypesEn[j] + ' option').each(function(k){
if( !$(this).is(':selected') ){
if( $(this).val() == selectedValue && $(this).val() != 0 ){
$(this).prop('disabled', 'true');
console.log('disabled: ' + $(this).val() );
}
}
});
}
}
}
});
Any help is much appreciated!
After enabling all the options, you need to go through all the menus, get their selected values, and re-disable all of them in the other menus, not just the one you just changed.
$(document).ready(function () {
$('#nomineeInfo').on('change', '.positionTypes', function () {
// Get the selected options of all positions
var allSelected = $(".positionTypes").map(function () {
return $(this).val();
}).get();
// set all enabled
$(".positionTypes option").removeAttr("disabled");
// Disable selected options in other positions
$(".positionTypes option:not(:selected):not([value='0'])").each(function () {
if ($.inArray($(this).val(), allSelected) != -1) {
$(this).attr('disabled', true);
}
});
});
});
DEMO
try
$("select.positionTypes").change(function () {
$("select.positionTypes option").prop('disabled', false);
$("select.positionTypes option:selected:not([value='0'])").each(function (i) {
$("select.positionTypes option:nth-child(" + ((+this.value) + 1) + ")").prop('disabled', true)
});
});
DEMO
Try this too, an optimized version
$("select.positionTypes").change(function () {
$("select.positionTypes option[value='" + $(this).data('index') + "']").prop('disabled', false);
$(this).data('index', this.value);
$("select.positionTypes option[value='" + this.value + "']:not([value='0'])").prop('disabled', true);
});
DEMO
Your html structure, classes and attempt is not bad but if you are using jQuery you should use its full advantages like .each function to make your live alot easier.
I would make an attempt like this:
$('.positionTypes').on('change', function () { //When any select changes...
var changedID = $(this).attr("id"); //Save id of select that was changed...
var selectedValue = $(this).val(); //Save value of select was changed...
if($(this).val() != "0") { //If we did not select a 0 value at all...
$('.positionTypes option').prop("disabled", false); //Enable all disabled options of all selects...
$('.positionTypes').each(function() { //Loop all existing selects
if($(this).attr("id") != changedID) { //If the select id is not our own select
$("#" + $(this).attr("id") + " option").each(function() { //loop all options of all selects except the one excluded by previous if clause
if($(this).attr("value") == selectedValue) { //if the value matches to saved value
$(this).prop("disabled", true); //Disable this one
}
});
}
});
};
});
I am not sure if this is 100% complete atleast it can disable options of other selects with identical value with a little bit more structured code.

Show/hide depending on dropdown menu selection

So I have a dropdown menu. The id for this dropdown menu is "courses". This dropdown also has an additional attribute, onclick="displayField();
The dropdown has 2 options.
2 and 3.
Now, I want everything with the class rsform-block-cotecours1 to be hidden depending on which option is chosen.
Here is the JavaScript for that:
function displayField()
{
if(document.getElementById("courses").text == '2';)
document.getElementsByClassName('rsform-block-cotecours1').style.display="none";
if(document.getElementById("courses").text == '3';)
document.getElementsByClassName('rsform-block-cotecours1').style.display="";
}
window.addEvent('domready', function() {
displayField();
});
However, this doesn't work, and I don't know why.
Is this what you are looking for?
Fiddle: fiddle
<select id="courses" onchange="ddlChange()">
<option value="2">2</option>
<option value="3">3</option>
</select>
JavaScript
function ddlChange() {
if (document.getElementById("courses").value =="2"){
document.getElementsByClassName('rsform-block-cotecours1')[0].style.display="none";
alert(document.getElementById("courses").value );
}
if (document.getElementById("courses").value == "3"){
document.getElementsByClassName('rsform-block-cotecours1')[0].style.display="block";
alert(document.getElementById("courses").value );
}
}
Change the code to following and test
function displayField()
{
if(document.getElementById("courses").value == '2';)
document.getElementsByClassName('rsform-block-cotecours1')[0].style.display="none";
if(document.getElementById("courses").value == '3';)
document.getElementsByClassName('rsform-block-cotecours1')[0].style.display="";
}
window.addEvent('domready', function() {
displayField();
});
in case you want to access the ext and not the value of dropdown list in javascript, then use following code to access the text of selected option from drop down
var courseElement = document.getElementById("courses");
var text = "";
if (courseElement.selectedIndex != -1)
{
text = courseElement.options[courseElement.selectedIndex].text;
}

Categories