Select multiple items using "shift" key - javascript

I use select2 v.3.5.1 and need to select multiple items. I wonder, is it possible to select multiple items using shift key? I don't want to have a multiple select, just select a few options while holding shift key. A code snippet is much appreciated.

If I understood correctly the answer a possible solution can be based on:
add a data-maxitem to your select
add a delegated event listener in order to detect the shit key when selecting
on select2-selecting test if the event must be prevented
at the end write the result into the div
$(document).on('keyup keydown', ".select2-drop-active", function (e) {
console.log('shift: ' + e.shiftKey);
if (e.shiftKey) {
$("#mySelect1").attr('multiple', 'multiple');
} else {
$("#mySelect1").removeAttr('multiple');
}
})
$("#mySelect1").select2()
.on('select2-selecting', function (e) {
var maxItem = $('#mySelect1').data('maxitem');
var shiftKey = $("#mySelect1").attr('multiple') == 'multiple';
var seletedOpt = $('.select2-drop-active .mySelected').length;
console.log('maxItem: ' + maxItem + ' shiftKey: ' + shiftKey + ' seletedOpt: ' + seletedOpt);
if (shiftKey && seletedOpt < maxItem) {
$('.select2-drop-active .select2-highlighted').addClass('mySelected');
if ($('.select2-drop-active .mySelected').length >= maxItem) {
$("#mySelect1").removeAttr('multiple');
var selectedOption = $('.select2-drop-active .mySelected').map(function (idx, ele) {
return ele.textContent;
}).get().join(' ');
setTimeout(function() {
$('.select2-container a span:first').text(selectedOption);
}, 100, selectedOption);
} else {
e.preventDefault();
}
} else {
$("#mySelect1").removeAttr('multiple');
}
});
.mySelected {
background: #3875d7;
color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://rawgit.com/cdnjs/cdnjs/master/ajax/libs/select2/3.5.1/select2.min.css" rel="stylesheet"/>
<script src="https://rawgit.com/cdnjs/cdnjs/master/ajax/libs/select2/3.5.1/select2.min.js"></script>
<select id="mySelect1" data-maxitem="2" style="width: 100%;">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>

You can do it by holding the ctrl key.
Thats the default key to press if you're picking individual items in a list in other programs anyway.

I was trying to accomplish this in 2022. I searched extensively, and none of the solutions quite worked for me, probably due to changes in the latest version of select2, I suspect. After much experimentation, I came up with a solution that works, and it also works when you have multiple select2 widgets on the same page.
The solution will set each select2 widget on the page to select each item between two items, by holding down the shift key. You can release the shift key after select the first item, in case you need to across the list as long as you hold it down again before clicking the second item. It works whether you select the first item as the one farther down in the list or the one higher up in the list.
It also requires that each select2 has an id, and is given the class "select2multiplewidget" (or you could use some other shared class name if you modified the javascript code below)
Note that I am using django in my app, so it is possible that the specific class names being used are from django's implementation, though I doubt this is the case.
Javascript
var count_shift = 0;
var shift_array = [];
$(document).ready(function() {
//
// Tell your app whether or not the shift key is being held down
$('.select2-search__field').on('keydown', function(e) {
if (e.keyCode === 16) {
isShiftDown = true;
}
}).on('keyup', function(e) {
if (e.keyCode === 16) {
isShiftDown = false;
}
});
// This event is used when the text box doesn't has focus.
$(window).on("keydown", function(e) {
if (e.keyCode === 16) {
isShiftDown = true;
}
}).on("keyup", function(e) {
if (e.keyCode === 16) {
isShiftDown = false;
}
});
//
// Event handlers to select a range of items
$('.select2multiplewidget').each(function() {
$(this).on('select2:closing', function () {
// To be exact, there's no need to return true.
return !isShiftDown;
}).on("select2:select", function (e) {
if (isShiftDown) {
var _id = $(document).find('li.select2-results__option--highlighted').attr('data-select2-id');
var _n = parseInt(_id.split('-')[4]);
shift_array.push({
id: _id,
data: e.params.data,
n: _n
});
count_shift++;
}
if (count_shift == 2) {
var lower = (shift_array[0].n < shift_array[1].n ? shift_array[0].n : shift_array[1].n);
var higher = (shift_array[1].n > shift_array[0].n ? shift_array[1].n : shift_array[0].n);
//
// Get current selections
var curVals = $(this).val();
for(var i = lower+1; i < higher; i++)
curVals.push(i.toString());
$(this).val(curVals);
$('#select2-' + this.id + '-results').find('.select2-results__option').each(function() {
var thisn = parseInt($(this).attr('data-select2-id').split('-')[4]);
if((thisn > lower) && (thisn < higher)) {
$(this).attr('aria-selected', 'true');
}
});
$(this).trigger("change");
$(this).select2('close');
count_shift = 0;
shift_array = [];
}
});
});
});
HTML (I generated mine using the Select2MultipleWidget in forms.py, you can see that at the bottom if it's relevant to you, I am using a form factory function. This is an example of one of the fields after it is rendered)
<div id="div_id_region_definition_0" class="form-group"> <div class=""> <select name="region_definition_0" lang="None" data-minimum-input-length="0" data-theme="default" data-allow-clear="false" data-maxitem="48" multiple="" class="select2multiplewidget form-control custom-select django-select2 select2-hidden-accessible" required="" id="id_region_definition_0" data-select2-id="id_region_definition_0" tabindex="-1" aria-hidden="true"> <option value="1">Alabama</option> <option value="2">Alaska</option> <option value="3">Arizona</option> <option value="7" selected="" data-select2-id="2">Connecticut</option> <option value="8">Delaware</option> <option value="9">Florida</option> <option value="10">Georgia</option> <option value="11">Hawaii</option> <option value="12">Idaho</option> <option value="13">Illinois</option> <option value="14">Indiana</option> <option value="15">Iowa</option> <option value="16">Kansas</option> <option value="17">Kentucky</option> <option value="18">Louisiana</option> <option value="19" selected="" data-select2-id="3">Maine</option> <option value="20">Maryland</option> <option value="21" selected="" data-select2-id="4">Massachusetts</option> <option value="22">Michigan</option> <option value="23">Minnesota</option> <option value="24">Mississippi</option> <option value="25">Missouri</option> <option value="26">Montana</option> <option value="27">Nebraska</option> <option value="28">Nevada</option> <option value="29" selected="" data-select2-id="5">New Hampshire</option> <option value="30" selected="" data-select2-id="6">New Jersey</option> <option value="31">New Mexico</option> <option value="32" selected="" data-select2-id="7">New York</option> <option value="33">North Carolina</option> <option value="34">North Dakota</option> <option value="35">Ohio</option> <option value="36">Oklahoma</option> <option value="37">Oregon</option> <option value="38" selected="" data-select2-id="8">Pennsylvania</option> <option value="39" selected="" data-select2-id="9">Rhode Island</option> <option value="40">South Carolina</option> <option value="41">South Dakota</option> <option value="42">Tennessee</option> <option value="43">Texas</option> <option value="44">Utah</option> <option value="45" selected="" data-select2-id="10">Vermont</option> <option value="46">Virginia</option> <option value="47">Washington</option> <option value="48">Washington DC</option> <option value="49">West Virginia</option> <option value="50">Wisconsin</option> <option value="51">Wyoming</option>
</select><span class="select2 select2-container select2-container--default select2-container--focus" dir="ltr" data-select2-id="1" style="width: 562.5px;"><span class="selection"><span class="select2-selection select2-selection--multiple" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="-1" aria-disabled="false"><ul class="select2-selection__rendered"><li class="select2-selection__choice" title="Maine" data-select2-id="472"><span class="select2-selection__choice__remove" role="presentation">×</span>Maine</li><li class="select2-selection__choice" title="Massachusetts" data-select2-id="473"><span class="select2-selection__choice__remove" role="presentation">×</span>Massachusetts</li><li class="select2-selection__choice" title="New Hampshire" data-select2-id="474"><span class="select2-selection__choice__remove" role="presentation">×</span>New Hampshire</li><li class="select2-selection__choice" title="New Jersey" data-select2-id="475"><span class="select2-selection__choice__remove" role="presentation">×</span>New Jersey</li><li class="select2-selection__choice" title="New York" data-select2-id="476"><span class="select2-selection__choice__remove" role="presentation">×</span>New York</li><li class="select2-selection__choice" title="Pennsylvania" data-select2-id="477"><span class="select2-selection__choice__remove" role="presentation">×</span>Pennsylvania</li><li class="select2-selection__choice" title="Rhode Island" data-select2-id="478"><span class="select2-selection__choice__remove" role="presentation">×</span>Rhode Island</li><li class="select2-selection__choice" title="Vermont" data-select2-id="479"><span class="select2-selection__choice__remove" role="presentation">×</span>Vermont</li><li class="select2-search select2-search--inline"><input class="select2-search__field" type="search" tabindex="0" autocomplete="off" autocorrect="off" autocapitalize="none" spellcheck="false" role="searchbox" aria-autocomplete="list" placeholder="" style="width: 0.75em;"></li></ul></span></span><span class="dropdown-wrapper" aria-hidden="true"></span></span> <small id="hint_id_region_definition_0" class="form-text text-muted">Select all of the states to include in this region. You can select multiple at once by holding control or shift. Filter the list by typing into the field.</small> </div> </div>
Perhaps this would be more useful... this is the source code. The above is what I get when I inspect element (sorry for such long lines, I am trying to post this to help someone, but I am behind schedule and don't have time to prettify it right now!):
<div
class="form-group col-xl-5" > <div id="div_id_region_label_0" class="form-group"> <div class=""> <input type="text" name="region_label_0" value="Northeast" maxlength="50" minlength="2" class="textinput textInput form-control" required id="id_region_label_0"> <small id="hint_id_region_label_0" class="form-text text-muted">Enter the reporting label for this region.</small> </div> </div> </div> <div
class="form-group col-xl-5" > <div id="div_id_region_definition_0" class="form-group"> <div class=""> <select name="region_definition_0" lang="None" data-minimum-input-length="0" data-theme="default" data-allow-clear="false" data-maxitem="48" multiple class="select2multiplewidget form-control custom-select django-select2" required id="id_region_definition_0"> <option value="1">Alabama</option> <option value="2">Alaska</option> <option value="3">Arizona</option> <option value="7" selected>Connecticut</option> <option value="8">Delaware</option> <option value="9">Florida</option> <option value="10">Georgia</option> <option value="11">Hawaii</option> <option value="12">Idaho</option> <option value="13">Illinois</option> <option value="14">Indiana</option> <option value="15">Iowa</option> <option value="16">Kansas</option> <option value="17">Kentucky</option> <option value="18">Louisiana</option> <option value="19" selected>Maine</option> <option value="20">Maryland</option> <option value="21" selected>Massachusetts</option> <option value="22">Michigan</option> <option value="23">Minnesota</option> <option value="24">Mississippi</option> <option value="25">Missouri</option> <option value="26">Montana</option> <option value="27">Nebraska</option> <option value="28">Nevada</option> <option value="29" selected>New Hampshire</option> <option value="30" selected>New Jersey</option> <option value="31">New Mexico</option> <option value="32" selected>New York</option> <option value="33">North Carolina</option> <option value="34">North Dakota</option> <option value="35">Ohio</option> <option value="36">Oklahoma</option> <option value="37">Oregon</option> <option value="38" selected>Pennsylvania</option> <option value="39" selected>Rhode Island</option> <option value="40">South Carolina</option> <option value="41">South Dakota</option> <option value="42">Tennessee</option> <option value="43">Texas</option> <option value="44">Utah</option> <option value="45" selected>Vermont</option> <option value="46">Virginia</option> <option value="47">Washington</option> <option value="48">Washington DC</option> <option value="49">West Virginia</option> <option value="50">Wisconsin</option> <option value="51">Wyoming</option>
</select> <small id="hint_id_region_definition_0" class="form-text text-muted">Select all of the states to include in this region. You can select multiple at once by holding control or shift. Filter the list by typing into the field.</small> </div> </div> </div> </div>
Django specifics - forms.py. This is generating a series of select2 multiple dropdowns to specify region groupings of states or DMAs or counties. The above HTML snippet is when the regions are made up of US states. This is provided as an example of how the field could be defined and is in the context of a larger process.
i = 0
while i < instance.num_regions:
if def_type != 'zips':
self.fields['region_definition_%d' % (i)] = forms.MultipleChoiceField(
label="",
help_text="Select all of the %s to include in this region. You can select multiple at once by holding control or shift. Filter the list by typing into the field." % (_word),
widget=Select2MultipleWidget(attrs={'data-maxitem': len(TEMP_CHOICES), 'multiple': 'multiple'}),
choices=TEMP_CHOICES,
initial=([] if (len(instance.region_definitions) < i+1) else models.mask_region_choices(TEMP_CHOICES, instance.region_definitions[i].split(','))),
required=True,
)
Hopefully this helps point someone on the right path. I didn't test this code in a standalone page but it works great in the context of the app I am developing.

Related

Hide select options based on previous selections

Is it possible to hide options in a select/dropdown with jQuery based on the user's selection from a previous dropdown e.g:
If user is 8 (Age Select/Dropdown), and chooses subject English (Subject Select/Dropdown) then hide Location 2 from (Locations dropdown)?
<select name="age">
<option value="8">8</div>
<option value="9">9</div>
<option value="10">10</div>
<option value="11">11</div>
</select>
<select name="subject">
<option value="eng">English</div>
<option value="maths">Maths</div>
<option value="science">Science</div>
</select>
<select name="subject">
<option value="loc-1">Location One</div>
<option value="loc-2">Location Two</div>
<option value="loc-3">Location Three</div>
</select>
Thank you!
you just need to add change function to your drop-down and according to your requirement you need to add your logic. see below example.
$(document).ready(function(){
$("#age").change(function(){
hideOption();
})
$("#subject").change(function(){
hideOption();
})
})
function hideOption(){
var age=$("#age").val();
var subject=$("#subject").val();
if(age==8 && subject=="Maths"){
$("#location [value='Location Two']").hide();
}
else{
$("#location [value='Location Two']").show();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="age" id='age'>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
</select>
<select name="subject" id='subject'>
<option value="English">English</option>
<option value="Maths">Maths</option>
<option value="Science">Science</option>
</select>
<select name="Location" id='location'>
<option value="Location One">Location One</option>
<option value="Location Two">Location Two</option>
<option value="Location Three">Location Three</option>
</select>
You can do something like below
$(document).on('change', '.age', function(e){
var val = $(this).val();
var subject = $('.subject').find(":selected").val();
if(val == 8 && subject == 'English' ){
$('.location option[value="Two"]').hide();
} else {
$('.location option[value="Two"]').show();
}
})
$(document).on('change', '.subject', function(e){
var age = $('.age').find(":selected").val();
var val = $(this).val();
if(age == 8 && val == 'English' ){
$('.location option[value="Two"]').hide();
} else {
$('.location option[value="Two"]').show();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="age" class="age">
<option >select</8>
<option value="8">8</8>
<option value="9">9</8>
<option value="10">10</8>
<option value="11">11</8>
</select>
<select name="subject" class="subject">
<option value="English">English</8>
<option value="Maths">Maths</8>
<option value="Science">Science</8>
</select>
<select name="location" class="location">
<option value="One">Location One</8>
<option value="Two">Location Two</8>
<option value="Three">Location Three</8>
</select>
With jQuery you can use .hide() and .show() to toggle element visibility. First however, you can check if the value of a select (for example age) was changed. Based on the logic you want to have, you can for example check what the value of the change was and do something if it matches a condition.
For example:
$( "#age-select" ).change(function() {
var value = $(this).val();
if(value == 8) {
$("#location-two").hide();
} else {
$("#location-two").show();
}
});
However, notice that I added an id for the "Location Two" option ("location-two") and for the age select element. Also, to make this work properly, you have to fix the values so that they're not all 8 and fix the closing tags of the elements (not ).

Adding and/or removing entire drop down select list

I want when a user clicks a button to be able to add or remove a drop down list for language select and proficiency. What js. code will work for me?
I have tried a couple of different codes from different sources but to no avail!
function addLanguage() {
var x = document.getElementById("dynamic-select");
x.labels[x.labels.length] = new Label('-- Choose a Language --', '0', false, false);
}
function removeLanguage() {
var x = document.getElementById("dynamic-select");
x.labels[x.labels.length - 1] = null;
}
function removeAllAddedLanguages() {
var x = document.getElementById("dynamic-select");
x.labels.length = 0;
}
<div id="dynamic-select">
<label for="dynamicSelect">
<select data-placeholder="Choose a Language...">
<option selected disabled value="">-- Choose a language --</option>
<option value="AF">Afrikanns</option>
<option value="SQ">Albanian</option>
<option value="AR">Arabic</option>
<option value="HY">Armenian</option>
<option value="EU">Basque</option>
<option value="BA">Bemba</option>
<option value="BN">Bengali</option>
</select>
<label for="proficiency">Level of proficiency</label>
<select name="pLevel" id="pLevel">
<option value="fluent">Fluent</option>
<option value="fluent">Fluent</option>
<option value="fluent">Fluent</option>
<option value="fluent">Novice</option>
<option value="fluent">No knowledge</option>
</select>
</label>
</div>
<button onclick="addLanguage()" id="" class="action_button">Add A Language</button>
<button onclick="removeLanguage()" style="background-color: orange" class="action_button">Remove Last Added</button>
<button onclick="removeAllAddedLanguages()" style="background-color: red" class="action_button">Remove Added Languages</button>
I'm not sure if you want to do this, but this adds a new selectlist with profession, however I didn't handeld the names of the selectlists, so you may need to add it if you want to post via form.
function addLanguage() {
var langContainer = document.getElementById('dynamic-select');
var firstLang = document.getElementsByClassName("lang")[0];
langContainer.append(firstLang.cloneNode(true));
}
function removeLanguage() {
var langs = document.getElementsByClassName("lang");
if (langs.length > 1) {
langs[langs.length - 1].remove();
}
}
function removeAllAddedLanguages() {
var langContainer = document.getElementById('dynamic-select');
var firstLang = document.getElementsByClassName("lang")[0];
langContainer.innerHTML = firstLang.outerHTML;
}
<div id="dynamic-select">
<div class="lang">
<label for="dynamicSelect">
<select data-placeholder="Choose a Language...">
<option selected disabled value="">-- Choose a language --</option>
<option value="AF">Afrikanns</option>
<option value="SQ">Albanian</option>
<option value="AR">Arabic</option>
<option value="HY">Armenian</option>
<option value="EU">Basque</option>
<option value="BA">Bemba</option>
<option value="BN">Bengali</option>
</select>
</label>
<label for="proficiency">Level of proficiency
<select name="pLevel" id="pLevel">
<option value="fluent">Fluent</option>
<option value="fluent">Fluent</option>
<option value="fluent">Fluent</option>
<option value="fluent">Novice</option>
<option value="fluent">No knowledge</option>
</select>
</label>
</div>
</div>
<button onclick="addLanguage()" id="" class="action_button">Add A Language</button>
<button onclick="removeLanguage()" style="background-color: orange" class="action_button">Remove Last Added</button>
<button onclick="removeAllAddedLanguages()" style="background-color: red" class="action_button">Remove Added Languages</button>
Why labels ? If you name the select correctly then this works
I left your inline event listeners but they could be moved to the script too. I change the buttons to type=button and gave the select an ID and used that
Also you had some illegal HTML (unclosed label)
// this code needs to be after the select is defined OR wrapped in an event listener
var x = document.getElementById("dynamicSelect");
var len = x.options.length; // default
function addLanguage() {
var lan = prompt("Language?","");
if (lan) {
x.options[x.options.length] = new Option(lan,lan)
x.selectedIndex=x.options.length-1;
}
}
function removeLanguage() {
if (x.options.length > 0) x.options.length--; // or x.options.length > len
}
function removeAllAddedLanguages() {
x.options.length = len;
x.selectedIndex=0;
}
<div id="dynamic-select">
<label for="dynamicSelect">Language spoken</label>
<select id="dynamicSelect" data-placeholder="Choose a Language...">
<option selected disabled value="">-- Choose a language --</option>
<option value="AF">Afrikanns</option>
<option value="SQ">Albanian</option>
<option value="AR">Arabic</option>
<option value="HY">Armenian</option>
<option value="EU">Basque</option>
<option value="BA">Bemba</option>
<option value="BN">Bengali</option>
</select>
<label for="proficiency">Level of proficiency</label>
<select name="pLevel" id="proficiency">
<option value="fluent">Fluent</option>
<option value="fluent">Fluent</option>
<option value="fluent">Fluent</option>
<option value="fluent">Novice</option>
<option value="fluent">No knowledge</option>
</select>
</label>
</div>
<button type="button" onclick="addLanguage()" id="" class="action_button">Add A Language</button>
<button type="button" onclick="removeLanguage()" style="background-color: orange" class="action_button">Remove Last Added</button>
<button type="button" onclick="removeAllAddedLanguages()" style="background-color: red" class="action_button">Remove Added Languages</button>

Disable specific option in specific dropdown

I'm working on a small website and I currently have two dropdowns in my form, both are below:
<select name="classType" id="classType" required>
<option value="" disabled selected>Select Your Class Type</option>
<option value = "Beginner">Beginner</option>
<option value = "Intermediate">Intermediate</option>
<option value = "Advanced">Advanced</option>
</select>
<br/>
<select name="studentType" id="studentType" required>
<option value="" disabled selected>Select Your Student Type</option>
<option value = "lowerLevel">Lower Level</option>
<option value = "upperLevel">Upper Level</option>
</select>
<br/>
I've experimented with some javascript but only at a beginner level. I was wondering if there's a way to disable a specific value in the studentType dropdown.
So for example if i select "Beginner" in the first dropdown then the option for "UpperLevel" in the second dropdown should be disabled.
This is what I tried, but it was not working:
var dropdown = document.getElementById("classType");
dropdown.onchange = function(event){
if (dropdown.value == "Beginner") {
// .....
Any ideas?
Thanks!
You can achieve this by hooking an event handler to the change event of the first select which sets the disabled property of the relevant option in the second select based on the chosen option, something like this:
$('#classType').change(function() {
$('#studentType option[value="upperLevel"]').prop('disabled', $(this).val() == 'Beginner')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="classType" id="classType" required>
<option value="" disabled="true" selected="true">Select Your Class Type</option>
<option value="Beginner">Beginner</option>
<option value="Intermediate">Intermediate</option>
<option value="Advanced">Advanced</option>
</select><br/>
<select name="studentType" id="studentType" required>
<option value="" disabled="true" selected="true">Select Your Student Type</option>
<option value="lowerLevel">Lower Level</option>
<option value="upperLevel">Upper Level</option>
</select><br/>
This should fit your needs:
http://codepen.io/themeler/pen/yOjWXB
<select name="classType" id="classType" required>
<option value="" disabled selected>Select Your Class Type</option>
<option value = "Beginner">Beginner</option>
<option value = "Intermediate">Intermediate</option>
<option value = "Advanced">Advanced</option>
</select>
<br/>
<select name="studentType" id="studentType" required>
<option value="" disabled selected>Select Your Student Type</option>
<option value="lowerLevel">Lower Level</option>
<option value="upperLevel">Upper Level</option>
</select>
<br/>
$(function () {
var $class = $('#classType'),
$student = $('#studentType');
$class.on('change', function () {
var $this = $(this),
$ul = $student.find('[value="upperLevel"]');
// clear value of student type on class type change
$student.find(':selected').prop('selected', false);
$student.find('option:first-child').prop('selected', true);
// lock / unlock position
if ($this.val() === 'Beginner') {
$ul.prop('disabled', true);
} else {
$ul.prop('disabled', false);
}
});
});
By jQuery:
$('#studentType option[value="upperLevel"]').attr('disabled','disabled');
Here is how I would do it, add a data-enabled tag to each option like this:
<select name="classType" id="classType" required>
<option value="" disabled selected>Select Your Class Type</option>
<option value = "Beginner" data-enabled="lowerLevel">Beginner</option>
<option value = "Intermediate" data-enabled="lowerLevel,upperLevel">Intermediate</option>
<option value = "Advanced" data-enabled="upperLevel">Advanced</option>
</select>
<br/>
<select name="studentType" id="studentType" required>
<option value="" disabled selected>Select Your Student Type</option>
<option value = "lowerLevel">Lower Level</option>
<option value = "upperLevel">Upper Level</option>
</select>
<br/>
And on change of the drop down, disable all options in the other drop down, then loop through and see if they're either in the enabled tag of the selected, or blank like this:
$('#classType').on('change', function(){
var allowed = $('#classType option:selected').attr('data-enabled').split(',');
$('#studentType option').attr('disabled','disabled');
$('#studentType option').each(function(){
if (allowed.indexOf($(this).val()) > -1 || !$(this).val()) {
$(this).removeAttr('disabled');
}
});
});

Populate HTML select Tag with first input

Filling every inputs of a working hours form can be quite tedious.
Is there a way to populate every inputs from a form with the first entered value?
In the case of this Fiddle https://jsfiddle.net/az8ujh1e/1/, a first input on any of the opend date would populate the other ones (that could still be modified one by one)
and a first input on the closed dates would do the same on all the closing dates.
Code:
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="col-sm-6">Opend</div>
<div class="col-sm-6">Closed</div>
<form role="form" action="#" method="POST">
<div class="col-sm-6" id="timeopen1">
<select name="timeopen1" class='selectpicker' >
<option value="00:00">00:00</option>
<option value="01:00">01:00</option>
<option value="02:00">02:00</option>
<option value="03:00">03:00</option>
<option value="04:00">04:00</option>
<option value="04:00">05:00</option>
<option value="04:00">06:00</option>
</select>
</div>
<div class="col-sm-6" id="timeclosed1">
<select name="timeclosed1" class='selectpicker' >
<option value="00:00">00:00</option>
<option value="01:00">01:00</option>
<option value="02:00">02:00</option>
<option value="03:00">03:00</option>
<option value="04:00">04:00</option>
<option value="04:00">05:00</option>
<option value="04:00">06:00</option>
</select>
</div>
<div class="col-sm-6" id="timeopen2">
<select name="timeopen2" class='selectpicker' >
<option value="00:00">00:00</option>
<option value="01:00">01:00</option>
<option value="02:00">02:00</option>
<option value="03:00">03:00</option>
<option value="04:00">04:00</option>
<option value="04:00">05:00</option>
<option value="04:00">06:00</option>
</select>
</div>
<div class="col-sm-6" id="timeclosed2">
<select name="timeclosed2" class='selectpicker' >
<option value="00:00">00:00</option>
<option value="01:00">01:00</option>
<option value="02:00">02:00</option>
<option value="03:00">03:00</option>
<option value="04:00">04:00</option>
<option value="04:00">05:00</option>
<option value="04:00">06:00</option>
</select>
</div>
<div class="col-sm-6" id="timeopen3">
<select name="timeopen3" class='selectpicker' >
<option value="00:00">00:00</option>
<option value="01:00">01:00</option>
<option value="02:00">02:00</option>
<option value="03:00">03:00</option>
<option value="04:00">04:00</option>
<option value="04:00">05:00</option>
<option value="04:00">06:00</option>
</select>
</div>
<div class="col-sm-6" id="timeclosed3">
<select name="timeclosed3" class='selectpicker' >
<option value="00:00">00:00</option>
<option value="01:00">01:00</option>
<option value="02:00">02:00</option>
<option value="03:00">03:00</option>
<option value="04:00">04:00</option>
<option value="04:00">05:00</option>
<option value="04:00">06:00</option>
</select>
</div>
<div class="col-sm-6" id="timeopen4">
<select name="timeopen4" class='selectpicker' >
<option value="00:00">00:00</option>
<option value="01:00">01:00</option>
<option value="02:00">02:00</option>
<option value="03:00">03:00</option>
<option value="04:00">04:00</option>
<option value="04:00">05:00</option>
<option value="04:00">06:00</option>
</select>
</div>
<div class="col-sm-6" id="timeclosed4">
<select name="timeclosed4" class='selectpicker' >
<option value="00:00">00:00</option>
<option value="01:00">01:00</option>
<option value="02:00">02:00</option>
<option value="03:00">03:00</option>
<option value="04:00">04:00</option>
<option value="04:00">05:00</option>
<option value="04:00">06:00</option>
</select>
</div>
<div class="col-sm-6"><br>
<button type="submit" class="btn btn-default" name="submit_time" >Submit</button>
</div>
</form>
I think the other answers are missing the point that he values should only be set automatically if the other values have not yet been set.
Add "timeopen" and "timeclosed" classes to your selectors like this:
<select name="timeopen1" class='selectpicker timeopen'>
Then the following script will change the other three values only if they are still set to "00:00".
$(function() {
$(".timeclosed, .timeopen").change(function() {
if ($(this).hasClass("timeopen")) {
autoSet(".timeopen", this);
} else {
autoSet(".timeclosed", this);
}
});
function autoSet(classSelector, t) {
if ($(classSelector + " option[value='00:00']:selected").length == 3) {
$(classSelector).val($(t).val());
}
}
});
This may cause a problem if three of them need to be set to "00:00", as it will then change the fourth one to "00:00" as well. So instead of checking the values, you may want to use global variables so that the autoSet only runs once for .timeopen and once for .timeclosed.
$(function() {
var autoSetTimeopen = true;
var autoSetTimeclosed = true;
$(".timeclosed, .timeopen").change(function() {
if ($(this).hasClass("timeopen") && autoSetTimeopen) {
autoSet(".timeopen", this);
autoSetTimeopen = false;
} else if ($(this).hasClass("timeclosed") && autoSetTimeclosed) {
autoSet(".timeclosed", this);
autoSetTimeclosed = false;
}
});
function autoSet(classSelector, t) {
if ($(classSelector + " option[value='00:00']:selected").length == 3) {
$(classSelector).val($(t).val());
}
}
});
If I correctly understood you want to display the value you selected in one field in all other fields from the same type. If so you just need to add a class "open" or "closed" to your select inputs and then proceed like this :
$('select').on('change', function() {
var value = $(this).val();
var className = 'open';
if( $(this).hasClass('closed') ) {
className = 'closed';
}
$('select.' + className).val(value);
});
Here is your Fiddle updated:
https://jsfiddle.net/az8ujh1e/2/
Here is a code which would do what you want, but it is not fully optimized right now. What I would do is, add ids to the select tags, so you can easily work with them with javascript or jquery.
$('#timeopen1 select').change(function(){
var opt = $(this).val()
for(i = 2; i<=4; i++){
$('#timeopen'+i.toString()+' select').val(opt);
}
});
$('#timeclosed1 select').change(function(){
var opt = $(this).val()
for(i = 2; i<=4; i++){
$('#timeclosed'+i.toString()+' select').val(opt);
}
});
EDIT:
Just as someone mentioned in another answer, add classes timeopen and timeclosed to your select elements, so we can easily work with them. Here is the updated code, to set all elements just the first time.
$('.selectpicker').one('change',function(event){
var opt = $(this).val()
if($(this).hasClass('timeopen'))
{
$('.timeopen').each(function(){
$(this).val(opt);
$(this).off('change');
});
}
else
{
$('.timeclosed').each(function(){
$(this).val(opt);
$(this).off('change');
});
}
});
https://jsfiddle.net/az8ujh1e/13/

Clear check mark and dropdowns when opposite radio button is chosen

How do I clear the checkmark in my checkbox when clicking on the opposite radio button? For some reason I cannot get it to clear will someone please tell me what I am doing wrong? I also would like to know how to reset the dropdowns if there chosen as well I cannot get a good grasp on this syntax I guess :/ $("#div12 > .clearfix input:select").val(""); Where am I going wrong?
function showhideCOREForm(transferring_vehicle_license) {
if (transferring_vehicle_license == "Current") {
document.getElementById("div11").style.display = 'block';
document.getElementById("div12").style.display = 'none';
$("#div12 > #secondYearCB").prop("checked", false);
FC.wantsASecondYear = false;
} else if (transferring_vehicle_license == "Expired") {
document.getElementById("div12").style.display = 'block';
document.getElementById("div11").style.display = 'none';
$("#div6 > .clearfix input:text").val("");
}
}
<input type="radio" value="Current" name="transferring_vehicle_license" id="transferring_vehicle_license" required="yes" onclick="calculateTotal()" onchange="showhideCOREForm(this.value);"/><label for="transferring_vehicle_license">Current Registration</label>
<input type="radio" value="Expired" name="transferring_vehicle_license" id="notransferring_vehicle_license" onclick="calculateTotal()" onchange="showhideCOREForm(this.value);"/><label for="notransferring_vehicle_license">Expired Registration</label>
<div id="div12" style="display:none">
<div class="clearfix">
<label for='CMonths' class="labelDoubleIndent">Calculate Months:</label>
<select name="month1" id="month1" size="1">
<option value="">Choose a Month</option>
<option value="0">January</option>
<option value="1">February</option>
<option value="2">March</option>
<option value="3">April</option>
<option value="4">May</option>
<option value="5">June</option>
<option value="6">July</option>
<option value="7">August</option>
<option value="8">September</option>
<option value="9">October</option>
<option value="10">November</option>
<option value="11">December</option>
</select>
<select name="month2" id="month2" size="1">
<option value="">Choose an Option</option>
<option value="2">2</option>
<option value="14">14</option>
</select>
<select name="month3" id="month3" size="1">
<option value="">Choose an Option</option>
<option value="3">3</option>
<option value="15">15</option>
</select>
<div id="secondYear" class="labelDoubleIndent">
<b>Do you want to add a second year?</b>
Yes: <input type="checkbox" name="secondYear" id="secondYearCB" />
</div><!-- secondYear -->
</div>
</div>
<div id="div11" style="display:none">
</div>
You are using just wrong selector: the #secondYearCB is not a first child of #div12. Use descendant selector instead:
$('#div12 #secondYearCB').prop("checked", false);
The same reason is for select - select is not input! Use just:
$("#div12 > .clearfix select").val("");
Both selectors are wrong to the CHECKBOX and SELECT.
Checkbox, as you are using an ID in it, just use the ID:
$("#secondYearCB").prop("checked", false);
The Selects, they are not INPUT, so use only the "select" word.
$("#div12 > .clearfix > select").val("");
P.s.: I add ">" to get only the direct SELECT childs inner the ".clearfix" div, if you don't want this, just remove it.
Selector: >

Categories

Resources