Adding and/or removing entire drop down select list - javascript

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>

Related

Unable to fetch user input from drop-down list

I've been trying to fetch user input from a simple drop-down list to fill it into a <p> tag but can't seem to get it done.
The following is my javascript:
<script>
function changeText() {
var textDDL = document.getElementById("DDL1");
var text = textDDL.options[textDDL.selectedIndex].value;
var test = document.getElementById("test");
test.innerHTML = text;
}
</script>
The following is my HTML code:
<p class="first">
<label for="first">From</label>
<input list="countriesDL" name="country" class="form-control" type="text" id="DDL1">
<datalist id="countriesDL">
<option value="Afghanistan" class="form-control"></option>
<option value="Albania"></option>
<option value="Algeria"></option>
<option value="Aland Islands"></option>
<option value="American Samoa"></option>
<option value="Anguilla"></option>
<option value="Andorra"></option>
<option value="Angola"></option>
<option value="Antilles - Netherlands"></option>
<option value="Antigua and Barbuda"></option>
<option value="Antarctica"></option>
<option value="Argentina"></option>
<option value="Armenia"></option>
<option value="Australia"></option>
<option value="Taiwan"></option>
</datalist>
</p>
<button id="info2Btn" type="button" class="btn btn-warning leggo" style="color:black;" onClick="changeText()">Let's Go</button>
The codes would be triggered by a button press. I've tried reloading the page upon button press to see if it applies the user input, I've tried calling the function upon clicking the button. Can't seem to see what's wrong with it.
[UPDATED] Is this what you are trying?
function changeText() {
var textDDL = document.getElementById("DDL1");
var text = textDDL.value;
var test = document.getElementById("text");
test.innerHTML = text;
}
<p class="first">
<label for="first">From</label>
<input list="countriesDL" name="country" class="form-control" type="text" id="DDL1">
<datalist id="countriesDL">
<option value="Afghanistan" class="form-control"></option>
<option value="Albania"></option>
<option value="Algeria"></option>
<option value="Aland Islands"></option>
<option value="American Samoa"></option>
<option value="Anguilla"></option>
<option value="Andorra"></option>
<option value="Angola"></option>
<option value="Antilles - Netherlands"></option>
<option value="Antigua and Barbuda"></option>
<option value="Antarctica"></option>
<option value="Argentina"></option>
<option value="Armenia"></option>
<option value="Australia"></option>
<option value="Taiwan"></option>
</datalist>
</p>
<button id="info2Btn" type="button" class="btn btn-warning leggo" style="color:black;" onClick="changeText()">Let's Go</button>
<p id="text"></p>
Try
function changeText() {
document.getElementById("test").innerHTML = document.getElementById("DDL1").value;
}

Dropdown selection error

<p class="birthday_date">
<label for="birthday">Birthday</label>
<select id="months" class="dd">
<option value="">Month</option>
<option value="january">January</option>
<option value="february">February</option>
<option value="march">March</option>
<option value="april">April</option>
<option value="may">May</option>
<option value="june">June</option>
<option value="july">July</option>
<option value="august">August</option>
<option value="september">September</option>
<option value="october">October</option>
<option value="november">November</option>
<option value="december">December</option>
</select>
<input type="text" name="dy" id="date" placeholder="Day">
<input type="text" name="year" id="year" placeholder="Year">
<span id="birthday_error">you can't leave this empty.</span>
</p>
#months option[value=""] {
display: none;
}
$('#months').change(function () {
var selectedValue = $(this).val();
if (selectedValue == "") {
$(this).addClass('input_error');
$('#birthday_error').show();
}
});
when you click on dropdown if you select an option then fine if do not select an option in dropdown then show an error message and apply input_error CSS to dropdown like google sign up dropdown
1.No jQuery library is there. so code will not work.(so add jQuery library)
2.Extra # is there in your code.
3.Use $(this) instead of months variable.
And finally i hope you want like this:- (if selectbox have some value then hide error message and remove error class form select-box otherwise add error class to selectbox and show error message too):-
$(document).ready(function(){ // add this if you are adding code at top of the page not in bottom
$('#months').addClass('input_error');
$('#birthday_error').show();
$('#months').change(function () {
var selectedValue = $(this).val();
if (selectedValue == "") {
$(this).addClass('input_error'); //remove # and months variable and use $(this)
$('#birthday_error').show();
}else{
$(this).removeClass('input_error'); //remove class
$('#birthday_error').hide();//hide error message
}
});
});
.input_error{
border-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><!-- add jQuery library-->
<p class="birthday_date">
<label for="birthday">Birthday</label>
<select id="months" class="dd">
<option value="">Month</option>
<option value="january">January</option>
<option value="february">February</option>
<option value="march">March</option>
<option value="april">April</option>
<option value="may">May</option>
<option value="june">June</option>
<option value="july">July</option>
<option value="august">August</option>
<option value="september">September</option>
<option value="october">October</option>
<option value="november">November</option>
<option value="december">December</option>
</select>
<input type="text" name="dy" id="date" placeholder="Day">
<input type="text" name="year" id="year" placeholder="Year">
<span id="birthday_error">you can't leave this empty.</span>
</p>
Note:- pay attention to the comments given in code snippet

Select multiple items using "shift" key

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.

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/

get selected option from document.getElementsByTagName("option")

I have html code this is a part of it :
<select id="year_marine_second_choose" style="display: none">
<option value="" style="display:none;"></option>
<option value="103">Lectures</option>
<option value="104">Courses</option>
<option value="105">Sheets</option>
<option value="106">Others</option>
</select>
<select id="year_marine_third_choose" style="display: none">
<option value="" style="display:none;"></option>
<option value="107">Lectures</option>
<option value="108">Courses</option>
<option value="109">Sheets</option>
<option value="110">Others</option>
</select>
<select id="year_marine_fourth_choose" style="display: none">
<option value="" style="display:none;"></option>
<option value="111">Lectures</option>
<option value="112">Courses</option>
<option value="113">Sheets</option>
<option value="114">Others</option>
</select>
this is the javascript code where the problem is :
var get_value = document.getElementsByTagName("option");
alert(get_value[5].value);
this code get the value of the 6th option .. any idea of how to get the value of the selected option by the user not the [5]
Javascript arrays start counting from 0, so [0] is the first element. Which means you maybe need alert(get_value[4].value);
In case you need the selected option you can use:
var all_select = document.getElementsByTagName("select");
for (i = 0; i < all_select.length; i++) {
all_select[i].onchange = function () {
alert(this.value);
}
}
Demo here

Categories

Resources