How to get all different dropdown have selected value or not - javascript

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

Related

How to stop a user selecting a DropDown option without 'disabling' it?

Question Background:
I have two dropdown menus in my app. One is to allow a user to select a Minimum monetary selection and the other a Maximum monetary selection.
The Issue:
If a user selects a value in the Minimum dropdown i.e 4 that is larger than the value select in the Maximum dropdown lets say 3 as then I want to display a popup dialog to the user informing them they cannot do this and then stop the clicked item in the minimum dropdown from being selected.
I can see plenty of example using:
.disable
but I do do not want to 'grey out' any options just validate the clicked items each time and then stop the item from being selected.
Is this possible? Any help would be appreciated.
You can use the "change" event on the select menu to check the value and then decide what to do with this.
document.getElementById('your_dropdown_id').addEventListener('change', myfct);
Where "myfct" is the function testing the value.
like this?
var validate = true;
if ( FirstSelectedValue > SecondSelectedValue ){
alert('first selected value must be higher or equal to second value');
validate = false;
}
//whereever you pass the information to..
if (validate && your other options..){
//continue, first value is lower or equal to second value..
}
A better option would be to only populate the second value when the first value have been selected and only allow valid options.
I would solve this programmatically by handling clicks on the dropdown manually. For example:
$('.dropdown-min').on('click', function(e) {
e.preventDefault();
if($(e.target).val() < $('.dropdown-max').find(":selected").val()) {
$(e.target).attr('selected', 'selected');
}
});
You may do it like this:
JS Fiddle
// grab the two dropdowns with their classname on change event
$('.min-max').on('change', function() {
var $th = $(this),
id = $th.attr('id');
// pass the id and the value to the function
updateMinMax(id, parseInt($th.val()));
})
function updateMinMax(id, v) {
// determine the id of the other dropdown
var otherID = (id == 'minimum') ? 'maximum' : 'minimum',
thisDropdown = $('#' + id),
otherDropdown = $('#' + otherID);
// we need to make sure the other dropdown value is set so we need
// to add this condition otherDropdown.val() != ''
if (id == 'minimum' && otherDropdown.val() != '' && thisDropdown.val() > otherDropdown.val()) {
// if a selected value from minimum dropdown is MORE than
// the selected maximum value
alert('minimum cannot be greater than maximum');
// reset current dropdown selection
thisDropdown.val('');
} else if (id == 'maximum' && otherDropdown.val() != '' && thisDropdown.val() < otherDropdown.val()) {
// if a selected value from maximum dropdown is LESS than
// the selected minimum value
alert('maximum cannot be less than minimum');
thisDropdown.val('');
}
}
select{width:50px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Min:<select class="min-max" id="minimum">
<option></option><option value="0">0</option><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><hr>
Max:<select class="min-max" id="maximum">
<option></option><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>
<option value="9">9</option></select>

get unselected option from multiple select list

I have a multiple select list. When user unselects the selected option, I want to know the value of the unselected option made by user. How do I capture it?
My sample code is as below.
<select multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
I have following jquery code to allow user to select multiple options
$('option').mousedown(function(){
e.preventDefault();
$(this).prop('selected', $(this).prop('selected') ? false :true);
});
Mouse events aren't available cross browser
My suggestion would be always store array of previous values on the select.
On every change you can then compare to prior value array and once found update the stored array
$('#myselect').on('change', function() {
var $sel = $(this),
val = $(this).val(),
$opts = $sel.children(),
prevUnselected = $sel.data('unselected');
// create array of currently unselected
var currUnselected = $opts.not(':selected').map(function() {
return this.value
}).get();
// see if previous data stored
if (prevUnselected) {
// create array of removed values
var unselected = currUnselected.reduce(function(a, curr) {
if ($.inArray(curr, prevUnselected) == -1) {
a.push(curr)
}
return a
}, []);
// "unselected" is an array
if(unselected.length){
alert('Unselected is ' + unselected.join(', '));
}
}
$sel.data('unselected', currUnselected)
}).change();
DEMO
Great question, i wrote some codes for detecting unselected options using data attributes.
$('#select').on('change', function() {
var selected = $(this).find('option:selected');
var unselected = $(this).find('option:not(:selected)');
selected.attr('data-selected', '1');
$.each(unselected, function(index, value){
if($(this).attr('data-selected') == '1'){
//this option was selected before
alert("I was selected before " + $(this).val());
$(this).attr('data-selected', '0');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="select">
<option data-selected=0 value="volvo">Volvo</option>
<option data-selected=0 value="saab">Saab</option>
<option data-selected=0 value="opel">Opel</option>
<option data-selected=0 value="audi">Audi</option>
</select>
If I understand you correctly, you want the option that just got unselected, right?
if so, try this:
create a variable "lastSelectedValue" (or whatever you want to call it). When you select an option, assign to it, when you change the selected option, you can get the value and use it, and assign to it again
var lastSelectedOption = '';
$('select').on('change', function(){
//do what you need to do
lastSelectedOption = this.val();
});
here's a fiddle: https://jsfiddle.net/ahmadabdul3/xja61kyx/
updated with multiple: https://jsfiddle.net/ahmadabdul3/xja61kyx/
not sure if this is exactly what you need. please provide feedback
As mentioned by others, the key would be to compare the previous selected values with current value. Since you need to figure out the removed value, you can check if the lastSelected.length > currentSelected.length and then simply replace the currentSelected from the lastSelected to get the results.
var lastSelected = "";
$('select').on('change', function() {
var currentSelected = $(this).val();
if (lastSelected.length > currentSelected.length) {
var a = lastSelected.toString().replace(currentSelected.toString(),"");
alert("Removed value : " + a.replace(",",""));
}
lastSelected = currentSelected;
});
Working example : https://jsfiddle.net/DinoMyte/cw96h622/3/
You can try make it
$('#link_to_id').find('option').not(':selected').each(function(k,v){
console.log(k,v.text, v.value);
});
With v.text get the Text
With v.value get the Value

Need validation with select option,

my select option has value & text
<select id="roomType" class="roomType" name="roomType">
<option selected="selected" value="N/A">--Select--</option>
<option value="25">Deluxe</option>
<option value="26">Standard</option>
</select>
according to some validation it needs to selected value.
my js code
//This is some validation method to make default
$(".roomOccupanice").each(function(){
var $t = $(this),
$select = $t.next().find('select');
if ($t.text().toLowerCase() == roomOccOffline.toLowerCase()){ // this is met condition correctly
$select[0].selectedIndex = $select.find('option').index($select.find('option[value^="'+roomTypeOffline+'"]')[0]);
//roomTypeOffline = "Deluxe" i need to make this as selected 1
}
});
As far i understood, you get a text "Deluxe" and with it you need to select the value "25".
If that's the case, i would suggest you to use Jquery selector :contains()
JQuery:
var roomTypeOffline = "Deluxe";
//get the option value that contains the text Deluxe
var selectValue = $("#roomType option:contains('"+roomTypeOffline+"')").val();
//Select that option
$("#roomType").val(selectValue);
JsFiddle

how to add same onchange events to different select boxes

I want to add 'change' events to 4 select boxes. I have done it using bind().
But I want to call different functions on change of each select box.
Say function1() on change event of SelectBox1...
How should I do it?
I am new to javascript & jquery, so please help.
Thank you
Suppose your HTML like this:
HTML
<select id="selectBox1">
</select>
<select id="selectBox2">
</select>
<select id="selectBox3">
</select>
<select id="selectBox4">
</select>
jQuery
$('select[id^=selectBox]').on('change', function() {
// to get the id of current selectBox
var selectId = this.id;
if(selectId == 'selectBox1') {
function1();
} else if(selecId == 'selectBox2') {
function2();
}
// and so on
});
Some more
$('select[id^=selectBox]').on('change', function() {
// to get the selected value
var value = $.trim( this.value ); // $.trim() used to remove space
// from beginning and end
// you may not use
// to get selected option text
var optText = $('option:selected', this).text()
// to get the selectedIndex
var selIndex = this.selectedIndex;
// OR
var selIndex = $(this).prop('selectedIndex');
});
Note
Here, select[id^=selectBox] get select boxes, whose id start with selectBox. You may have something different id.
.change() used for bind the event to those select box.
Read more about
jQuery selectors
jQuery Events
$.trim()
.prop()
you can set an specific attribute for each select so:
<select id="selectBox1" val='1'>
</select>
<select id="selectBox2" val='2'>
</select>
<select id="selectBox3" val='3'>
</select>
<select id="selectBox4" val='4'>
</select>
and then bind onchange event like this:
$("select").change(function(){
var val = $(this).attr("val");
if (val == '1')
{
//logic for first select change
}
else if (val == '2')
{
//logic for second select change
}
else if (val == '3')
{
//logic for third select change
}
// and so on...
});
hope that helps.

Setting a SELECT element by text, not value

I'm sure this is relatively easy and straightforward, but I'm having no success figuring it out.
I am trying to set the selected option of a drop down list element using the following code:
if ($(this).attr("tagName") == "SELECT") {
oldValue = $(this).parent().parent().find('span.displayField').text();
$(this).val(oldValue).attr("selected", "selected");
return;
}
But it is not changing the select element at all. The code is definitely running, and oldValue is being populated appropriately.
Can anyone see what I might be missing?
Thanks!
UPDATE:
For clarification, here is the HTML:
<span class="displayField">Pending</span>
<span class="editField">
<select data-val="true" data-val-number="The field ProgramStatusId must be a number." data-val-required="The ProgramStatusId field is required." id="ProgramListViewModels_0__ProgramStatusId" name="ProgramListViewModels[0].ProgramStatusId">
<option value="1">Pending</option>
<option value="2">Tabled</option>
<option value="3">Approved</option>
<option value="4">Declined</option>
</select>
</span>
$(this).val(oldValue) will set the value of this to oldValue, and you just wanna find options with that texy. You want to use :contains() for this.
if ($(this).is('select')) {
oldValue = $(this).parent().parent().find('span.displayField').text();
$('option:contains('+oldValue+')', this).attr("selected", "selected");
return;
}
Or if there are multiple options that contain the text, but are different, try this:
if ($(this).is('select')) {
oldValue = $(this).parent().parent().find('span.displayField').text();
$('option', this).filter(function(){
return this.text === oldValue;
}).attr("selected", "selected");
return;
}
If I Understand your snippet correctly. I believe what you're trying to do is select the item with the same text() as $('span.displayField').
if ($(this).attr('tagName') == 'SELECT') {
// unselect previously selected element first.
var prev = $(this).find('option:selected').attr('selected', false);
// select item with text from span.displayField
var oldText = $(this).parent().parent().find('span.displayField').text();
var oldOption = $(this).find('option[text="' + oldText + '"]');
oldOption.attr('selected', true);
}
I dont understand what is that
).parent().parent().
if you just want to set select box value selected try these
http://api.jquery.com/val/
$('select.foo option:selected').val(); // get the value from a dropdown select
$('select.foo').val(); // get the value from a dropdown select

Categories