Moving option value on top of dropdown list using jQuery - javascript

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.

Related

How shoud I put a condition correlated with the select option value

I'm writing a code which reads a drop down value then perform some actions, and I try to figure out how to get the select option value and put a condition regarding to that one.
<script>
var e = document.getElementById("selectNewBalance");
var value = e.options[e.selectedIndex].value;
if (value == "Inserted values"){
/// from here to the return statement I know for sure it works but now i'm trying to apply this condition only when the select option is "Inserted values"
var checkThisOnes = ["Value1", "Value2", "Value3"];
var printThisOnes = []
var message = "Please fill these fields: "
$('#myform').submit(function() {
var result=true;
for (i = 0; i < checkThisOnes.length; i = i + 1) {
var checkedValue = $('#'+checkThisOnes[i]).val();
if (checkedValue === undefined || checkedValue === "") {
message = message + checkThisOnes[i]+ ", ";
result =false;
}
}
if (result === false) {
alert(message)
location.reload();}
return result;
});}
</script>
Reading the value from a dropdown is easier than how you did it:
var select = document.getElementById("selectNewBalance");
// add an event listener to the element
select.addEventListener('change', function(e) {
if (e.target.value === 'Inserted values') {
console.log('You can do something here')
}
})
<select id="selectNewBalance">
<option selected disabled>--</option>
<option value="Inserted values">Inserted values</option>
<option value="Other">Other</option>
</select>
With jQuery the snippet looks like:
jQuery('document').ready(function($) {
$('#selectNewBalance').on('change', function(e) {
if ($(this).val() === 'Inserted values') {
console.log('You can do something here')
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectNewBalance">
<option selected disabled>--</option>
<option value="Inserted values">Inserted values</option>
<option value="Other">Other</option>
</select>
That is all. The point is, you need to place your conditions in an event, like change, so it runs when the input value changes.

check if the values in an array are the same as the values as the values of a selectbox?

Is it possible to check if there is a match between values inside and array and values of a select box? I need to check if the value of the select box is in the array so if it is I can change its class to something else. noobie here
EDIT
I have been working on recreating my question so it can be more understandable.
On this fiddle here you can see that I am dynamically creating new selectboxes using a button! In each of the buttons, the selection is being disabled but only for that box. What I want to do is that if one value is selected all of the others will be deactivated, in all the other boxes.
I tried insert in an array all the values of the selected values and then compare them in order to disable them but I only managed to do it in each box. ALSO the data from the selectboxes come from a database!
any tips?
//this supposed to disable the selected options
$('#sig_3').on('change', '.c_service_c', function() {
var value = $('#type').val();
var selected_array = [];
$('.c_service_c option:selected').each(function() {
if ($(this).val() != "") { //$(this).val()!="" --> remove the check on 'Please Select' option
selected_array.push($(this).val()); //save selected values so that they can be disabled later
}
});
console.log('print: ' + selected_array);
//reset all values to 'Y' before changing selected to 'N'
$('.c_service_c option').each(function() {
if ($(this).val() != "") { //$(this).val()!="" --> remove the check on 'Please Select' option
$('.c_service_c option').addClass('Y'); //resetting all options to 'Y'
}
});
if (selected_array.indexOf($('.c_service_c').val()) > -1) {
$('.c_service_c option:selected').removeClass('Y');
$('.c_service_c option:selected').addClass('N');
console.log('it prints here too');
}
//disable all selected values in options array
if (selected_array.indexOf($(this).val()) > -1) {
$('.c_service_c option:selected').removeClass('Y');
$('.c_service_c option:selected').addClass('N');
console.log('it prints');
}
//disable all selected values
$('.c_service_c option').each(function() {
if ($(this).val() != "") { //$(this).val()!="" --> remove the check on 'Please Select' option
if ($(this).hasClass('N')) {
$(this).attr("disabled", true);
$(this).removeClass('N');
} else {
$(this).addClass('Y');
$(this).attr("disabled", false);
}
}
});
});
If you want for each options to check if the option exists in an array, and based on to disable it or not, you just need to loop over the options using .each() function and do your check.
This is how should be your code:
$("#dropdown option").each(function() {
if (arr.indexOf($(this).val()) > -1) {
$(this).attr('disabled', true);
}
});
var arr = ["apple", "tomato", "peach", "pineapple"];
$("#dropdown option").each(function() {
if (arr.indexOf($(this).val()) > -1) {
$(this).attr('disabled', true);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="dropdown">
<option value="apple">Apples</option>
<option value="orange">Oranges</option>
<option value="pineapple">Pineapple</option>
<option value="lemon">Lemon</option>
</select>
Edit:
I updated your fiddle so it's working now, your problem was that you declared selected_array in a local scope for $().each() it needs to be declared as global.
Assuming you're using jQuery as well, and assuming I understand correctly what you are asking, try the following:
//available values
var arr = ["apple", "tomato", "peach", "pineapple"];
$("#select-dropdown").on("change", function() {
//store value on local variable
var value = $(this).val();
//search the value inside the array, return -1 if can't find
var index = arr.indexOf(value);
if (index != -1) {
//found value in array, add the new class!
$(this).addClass("my-new-class");
} else {
//didnt found anything, remove class
$(this).removeClass("my-new-class");
}
});
.my-new-class{
background:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="select-dropdown">
<option value="apple">Apples</option>
<option value="orange">Oranges</option>
<option value="pineapple">Pineapple</option>
</select>

How to get unselected value in dropdown jquery

I am using following html for dropdown
<select class="form-control" id="iddeStatus" name="iddeStatus">
<option value="">--Select ID De-dup Status--</option>
<option value="PASSED">Passed</option>
<option value="FAILED">Failed</option>
</select>
And below is my jquery code to get dropdown value
var iddeStatus = $("#iddeStatus").val();
if((iddeStatus!=null)||(iddeStatus!="")){
...
}else{
...
}
Problem is, even if i dont select the value, control goes inside the if statement.
Reason for behaviour:
That is because you have or statement in if between if conditions. You need to use && condition instead of ||
if((iddeStatus!=null) && (iddeStatus!="")){
...
}
Solution:
You can narrow down the if condition to simply:
if(iddeStatus!="")){
...
}
You can check for truthyness of the value
var iddeStatus = $("#iddeStatus").val();
if (!iddeStatus) {
//not selected
} else {//no need to have the else block if you don't have anything to do here
//selected
}
or the opposite
var iddeStatus = $("#iddeStatus").val();
if (iddeStatus) {
//selected
} else {
//not selected
}
Please use below code to get unselected value in dropdown jquery.
var iddeStatus = $("#iddeStatus").val();
if((iddeStatus!=null)||(iddeStatus!="")){
var unSelected = $("#iddeStatus").find('option').not(':selected');
for (var i = 0; i < unSelected.length; i++) {
alert(unSelected[i].text)
}
}else{
alert('else part')
}

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.

Jquery : Need to check a list of values in a combo box

I am totally confused how to make it.. Here is my problem.
I have n number of customized combo boxes (Which creates dynamically from the server side). Now i want to store the values of each combo box and need to validate by client side. If any one of the combo box val() == 0(i mean no option selected), then i need to show an error message. If all the combo box values are selected, then i need to show a a div in a popup. All these actions have to be happened if i click the save button.
Since these combo boxes are rendering dynamically, i cannot use its ID. My idea is to give a class name called combo and need to validate. Here is my code,
HTML (dynamicaaly generated)
<select class="combo">
<option selected="selected" value="0"></option>
<option value="1">Employee First Name (HR)</option>
<option value="2">Employee last Name (HR)</option>
<option value="3">Employee number (HR)</option>
<option value="4">NINO (HR)</option>
</select>
jQuery
$(document).ready(function(){
$('#save').click(function(){
var myLength = $('.combo option:selected').length;
alert(myLength);
if(myLength > 0){
alert('popups here');
count=count+1;
alert(count);
var maskHeight = $(document).height();
var maskWidth = $(window).width();
$('#mask').css({'width':maskWidth,'height':maskHeight});
$('#mask').fadeTo("fast",0.8);
var winH = $(window).height();
var winW = $(window).width();
$('.popups').css('top',winH/2-$('.popups').height()/2);
$('.popups').css('left',winW/2-$('.popups').width()/2);
$('.popups').show();
}
else
{
alert('No popups');
}
return false;
});
});
The idea is not working. Please suggest how to proceed... Many thanks :)
var trace = false;
$('#save').on('click', function() {
$('select.combo').each(function() {
if(this.value == 0){
trace = true;
return;
}
});
if(trace) {
// all combo not selected
alert('Please select all combo');
trace = false;
} else {
// all selected
alert('Thanks..');
}
});
How about this approach:
$('#save').click(function(){
var comboLength = $('.combo').length;
var selectedLength = $('.combo option:selected[value!=0]').length;
if (comboLength == selectedLength) { /* code for valid case*/}
else { /*code for invalid case*/; return false;}
})
TRY
HTML
<select class="combo" multiple="multiple">
<option selected="selected" value="0" >--SELECT ONE--</option>
<option value="1">Employee First Name (HR)</option>
<option value="2">Employee last Name (HR)</option>
<option value="3">Employee number (HR)</option>
<option value="4">NINO (HR)</option>
​
jQuery
var foo = {};
$('#submit').live('click', function() {
$('select.combo').each(function(i) {
var selected = $(this).val();
foo[i] = selected;
});
//this will remove first value ( blank having value=0)
var finalOutput = jQuery.grep(foo[0], function(value) {
//this will unselect the blank value
$('.combo option:eq(0)').prop('selected', false);
return value != "0";
});
if ($.isEmptyObject(finalOutput)) {
alert('please select atlest one')
}
else {
alert('Output:' + finalOutput)
}
})​​
Working DEMO

Categories