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>
Related
CURRENT: Dropdown choice of 'Yes/No'.
'Yes' = Show 'additional' dropdown/inputs to be entered
'No' = Hide 'additional' dropdown/inputs
WANT: I want to make it so if the user chooses 'Yes', then enters something into the 'additional' dropdowns/inputs, but then decides to switch their original answer back to 'No', make it clear the 'additional' values.
This is so when the form submits, i wont be carrying over any values in the POST that aren't needed.
HTML
<section><style>.required {color:#ff0000;font-weight:bold;position:absolute;}</style>
<div class="section_header">LNB INFORMATION</div>
<label>Did you install an LNB?<span class="required">*</span> </label>
<select class="DropdownClass" name="lnb_choice" id="lnb">
<option disabled selected value="">Select... (Required)</option>
<option value="1">Yes</option>
<option value="0">No</option>
</select>
<br>
<div class="LNBChoice DivElement1">
<select class="DropdownClass qrt" name="lnb_type" id="lnb_type">
<option value="">Type...</option>
<option value="3D2RBLNB">REV 3 LNB</option>
<option value="5D2RBLNB">REV 5 LNB</option>
<option value="SL3S4NR2">SWM3 LNB</option>
<option value="SL5S4NR2">SWM5 LNB</option>
<option value="SL5K4NR1">KAKU LNB</option>
</select>
<input type="text" id="lnb_barcode" name="lnb_barcode" placeholder="LNB Serial..." class="scantype basic" />
</div>
</section>
JS + Jquery 1.10.1
$(".DropdownClass").change(function () {
if ($(this).attr('name') == 'lnb_choice') {
var number = $(this).val();
$('.LNBChoice').hide().slice( 0, number ).show();
}
});
JSFIDDLE: https://jsfiddle.net/ra1t9jfL/
Additional issue: This is all part of a ,
If there is an error, i return them back to this page, using &field=value on the url to return values to the corresponding text input boxes/dropdowns.
I am able to return the 'Yes' value to the dropbox, but it does not activate the 'Show additional jquery'.
So the user has to select, 'No' then back to 'Yes' for the 'additional' to show up.
Add these two lines before or after $('.LNBChoice').hide().slice( 0, number ).show();
$('#lnb_type').val('');
$('#lnb_barcode').val('');
To clear the additional fields when the user selects "No" from the first drop down, you can add this which will do that:
$('#lnb').change(function() {
if($(this).val() === '0') {
/* User selected "no" so reset the additional field values */
$('#lnb_type').val('');
$('#lnb_barcode').val('');
}
});
To initialise the form based on values passed from the query string of the URL (ie on return from error screen), you could take the following approach:
/* Add the following script to your page */
$(function() {
/*
Access query string of url, remove preceding "?", and split
query string by "&" to return an array of "field=value" sub-strings
if any exist. Iterate the array of these sub-strings with forEach
*/
location.search.slice(1).split('&').forEach(function(part){
/* Split current sub-string by "=" to obtain name and value */
var nameValue = part.split('=');
var name = nameValue[0];
var value = value[1];
/* Select form element by name and initialise the value */
$('[name="' + name + '"]').val(value);
});
});
<select class="distinctrank" name="rank[]" required>
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
<select class="distinctrank" name="rank[]" required>
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
<select class="distinctrank" name="rank[]" required>
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
I am trying to prevent the user to select the same option twice
EX:
value 1 -> B
value 2 -> C
value 3 -> A
But not allow
value 1 -> B
value 2 -> B
value 3 -> A
I can't use this: answer
because I have 8 <select> with 8 <option>and the user is allow to change his/her option.
Unfortunately, I can't use a single select set to "multiple".
I found this answer just now, but since I don't jquery or Javascript well, I can't make it work without the select tag inside a table:
Here is the answer
UPDATE:
I found a better way to do it, but I am having some problems.
I tried to modify this code: with input tags to make it work with select tags. The problem that I am facing now is that every time you select the same option twice, the error "Please enter a Unique Value" show up (I do want to see it, when the user select the same value twice or more) and when you change the value the "Please enter a Unique Value" does go away. But, It keep a "this field is required" warning behind (when a click a new select tag). So, "this field is required" doesn't go away until the user pick an option for all select tag.
Here is the Jquery code:
jQuery.e
jQuery.validator.addMethod("notEqualToGroup", function(value, element, options) {
// get all the elements passed here with the same class
var elems = $(element).parents('form').find(options[0]);
// the value of the current element
var valueToCompare = value;
// count
var matchesFound = 0;
// loop each element and compare its value with the current value
// and increase the count every time we find one
jQuery.each(elems, function() {
thisVal = $(this).val();
if (thisVal === valueToCompare) {
matchesFound++;
}
});
// count should be either 0 or 1 max
if (this.optional(element) || matchesFound <= 1) {
//elems.removeClass('error');
return true;
} else {
//elems.addClass('error');
}
}, jQuery.validator.format("Please enter a Unique Value."))
// validate form
$("#signupform").validate({
rules: {
'rank[]': {
required: true,
notEqualToGroup: ['.distinctrank']
},
},
});
I wonder if you could simply use a single select set to "multiple"...
<select multiple class="form-control" name="rank[]">
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
It seems appropriate :-)
Your code...
rules: {
'rank[]': { // <-- will only match one of your three
required: true, ....
You cannot have three different select element all share the same name, in your case, rank[].
The jQuery Validate plugin requires that every form data input element contain a unique name. It's how the plugin keeps track of the form inputs, and there is no workaround for this. You'll have to include an index or change the name.
rules: {
'rank[1]': {
// rules
},
'rank[2]': {
// rules
},
'rank[3]': {
// rules
}
}
If the same rules are used on all three, then you can use the .rules() method to apply them all at once...
$("#signupform").validate({ // plugin initialization
// other rules & options
});
$('[name^="rank"]').each(function() {
$(this).rules('add', {
required: true,
notEqualToGroup: ['.distinctrank']
});
});
$('[name^="rank"]') matches all elements that have a name that "starts with" rank. Then .each() applies the rule to every instance matched by the selector.
You can try something like this:
$(document).ready(function() {
$('select').change(function() {
self = $(this);
choosen = $(this).val();
$('select').not(self).each(function() {
if ($(this).val() == choosen) {
// $(this).prop('disabled', true);
alert('Option is already selected');
$(self).val($(this).find("option:first").val());
}
});
});
});
This is actually partial implementation of code you found in another answer. Commented line would disable already selected options, but... then users can't change their minds... However i would probably use that commented line (edit:probably not, it causes other problems), rather than annoying alerts -> because, with alerts - if user tries to change his mind - user experience is not so great, again...
DEMO: http://jsfiddle.net/dq9j4s32/2
I have this select input. It will be put in the form multiple times since they also have quantity each.
So the select input will be shown again but i want it to restrict an option that is already selected. Not necessarily to hide the selected input but to prompt an alert whenever the user chooses an option which is already in the form.
<select class="form-control" name="supplier[]" id="supplier[]">
<option value="0">Select Item</option>
#foreach ($items as $item)
<option value="{{{ $item->id }}}">{{{ $item->code}}} - {{{ $item->description}}}</option>
#endforeach
</select>
Build a dictionary of values => counts and when adding to the dictionary check if the key already exists.
Something like this should work:
var counts = {};
$("select[name='supplier[]']").each(function(i, el) {
var val = $(el).val();
if (typeof counts[val] == 'undefined') {
counts[val] = 1;
} else {
alert('value ' + val + ' entered more than once');
}
});
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;
}
});
I have the following multi select and I am using Jquery Chosen plugin
<select multiple="multiple" class="chzn-select span3" name="requestCategory" id="requestCategory">
<option selected="selected" value="">All</option>
<option value="2">Electrical</option>
<option value="4">Emails</option>
<option value="3">Filming Permits</option>
<option value="10">test1</option>
</select>
Client wants to make sure that i do not allow user to select ALL if any other value is selected or if user selects any other value then automatically deselect/remove ALL; because ALL = all categories so having individual option does not make sense. How do i do this?
Check if more than one item is selected, or if only one item is selected that it is not the first one - in these cases disable All.
$('.chzn-select').on('change', function() {
var selectedOpts = $('option:selected', this);
if(selectedOpts.length > 1 || selectedOpts.first().index() !== 0) {
$('option', this).first().attr('disabled', 'disabled');
}
});
http://jsfiddle.net/zCk2z/5/
at first change of option [simple] removes the All category.
but i recomand to disable the item, it looks better use .attr('disabled', 'disabled') instead of .remove();
$('#requestCategory').change(
function(){
$(this).find('option:contains("All")').remove()
})