Code where <select> changes options in another <select> - javascript

I have made same code in Javascript that will change options in drop-down list of cities when user changes state.
The problem with the code is that it won't work. I think that code is OK, but I am very new in JavaScript, so I can't see the error.
Can you please check my code and see where I made error. Thanks.
JavaScript:
function drzava_promjena() {
var obj_state = document.getElementById("id_drzava")
var index = obj_states.selectedIndex;
var value_state = obj_state.options[index].value;
towns = town_list[value_state];
var obj_town = document.getElementById("id_gradovi");
while (obj_town.options.length > 0) {
obj_town.remove(0);
}
var new_value;
for (var i = 0; i < towns.length; i++) {
new_value = document.createElement("option");
new_value.value = towns[i];
new_value.text = towns[i];
try {
obj_town.add(new_value);
} catch (e) {
obj_town.appendChild(new_value);
}
}
And this is HTML:
<select id="id_drzava" onchange="drzava_promjena(this);">
<option value="Austrija">Austrija</option>
<option value="Njemacka">Njemacka</option>
<option value="Slovenija">Slovenija</option>
<option value="Ceska">Ceska</option>
</select>
<br>
<select id="id_gradovi" onchange="">
<option value="0"></option>
</select>
<br>
<select id="id_uni" onchange="">
<option></option>
</select>

Try the following code. I've also put up a fiddle to demonstrate.
JavaScript:
var populateCities = function (country, target_id) {
var i = 0, options, cities, selection, target;
cities = {
"usa": {
"dallas": "dal",
"san francisco": "sf",
"houston": "hou"
},
"fr": {
"paris": "pr",
"la riche": "lr"
}
};
selection = country.options[country.selectedIndex].value;
target = document.getElementById(target_id);
target.options.length = 0;
if(selection !== 'none') {
options = cities[selection];
for(var city in options) {
target.options[i] = new Option(city, options[city]);
i++;
}
}
}​
HTML:
<select id="country" onchange="populateCities(this, 'cities')">
<option selected value="none">Pick a country</option>
<option value="usa">USA</option>
<option value="fr">France</option>
</select>
<select id="cities"></select>

Related

Change selected option value in dropdown

My dropdown looks like,
<select name="speed" id="ddlCustomer" class="form-control select-basic">
<optgroup label="CustomerId OrderDate SupplyDate Supplier">
<option value="1011_2">1011 2015-12-18 2015-12-22 ABC</option>
<option value="1011_2">1034 2015-12-23 2015-12-28 XYZ</option>
</optgroup>
</select>
Currently the dropdown shows options like "1011 2015-12-18 2015-12-22 ABC", that is fine but when user selects an option, I need to show only "CustomerId" i.e, 1011 in this case.
Your help is really appreciated. Thanks
Added script for focusout
customSelect.focusout(function () {
customSelectOptions.each(function (options) {
if ($(this).is(':selected')) {
$(this).text($(this).attr('value').split('_')[0]);
$(this).blur();
}
});
});
var states = [];
var customSelect = $('#ddlCustomer');
var customSelectOptions = customSelect.children().children();
// Get each state then push them to the array
// Initial state declaration
customSelectOptions.each(function() {
var state = $(this).text();
states.push({ state: state });
if ($(this).is(':selected')) {
$(this).text($(this).attr('value').split('_')[0]);
}
});
// On focus, always retain the full state name
customSelect.on('focus', function() {
customSelectOptions.each(function(index) {
$(this).text(states[index].state);
});
// On change, append the value to the selected option
$(this).on('change', function() {
customSelectOptions.each(function(options) {
if ($(this).is(':selected')) {
$(this).text($(this).attr('value').split('_')[0]);
}
});
// Un-focus select on finish
$(this).blur();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="speed" id="ddlCustomer" class="form-control select-basic">
<optgroup label="CustomerId OrderDate SupplyDate Supplier">
<option value="1011_2">1011 2015-12-18 2015-12-22 ABC</option>
<option value="1034_2">1034 2015-12-23 2015-12-28 XYZ</option>
</optgroup>
</select>
Try like this.You have use regex with text value of selected option.
var ddlCustomer = document.querySelector('#ddlCustomer');
ddlCustomer.addEventListener('change',function(){
text = $(this).find("option:selected").text();
var value = text.match(/[0-9]+/);
$(this).find("option:selected").text(value);
alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="speed" id="ddlCustomer" class="form-control select-basic">
<optgroup label="CustomerId OrderDate SupplyDate Supplier">
<option value="1011_2">1011 2015-12-18 2015-12-22 ABC</option>
<option value="1011_2">1034 2015-12-23 2015-12-28 XYZ</option>
</optgroup>
</select>
See fiddle here https://jsfiddle.net/88cozeaz/1/
document.getElementById('#ddlCustomer').onchange = function() {
var option = this.options[this.selectedIndex];
option.setAttribute('data-text', option.text);
option.text =$(this).val();
// Reset texts for all other but current
for (var i = this.options.length; i--; ) {
if (i == this.selectedIndex) continue;
var text = this.options[i].getAttribute('data-text');
if (text) this.options[i].text = text;
}
};

Dropmenu get value from the list

Hello how can I select the value of Business by using the emplStatus2 GORM object?
<select name="emplStatus2" onchange="swapFieldsets(this.value, '#sa-email', '#sa-password')" class="form-control" id="emplStatus2">
<option value="Home">Send via Home Email</option>
<option value="Business">Send via Business Email</option>
<option value="Password">Set a password now,provide access information offline</option>
If you use jquery you can do it like this
$("#emplStatus2").val("Business")
if you only want javascript i think its something like this:
document.getElementById("emplStatus2").options.value = "Business"
please describe detail what you need.
You can check value
function swapFieldsets(elem) {
if (elem.value.toLowerCase() === 'business') {
alert(elem.value)
}
}
On fiddle https://jsfiddle.net/xw0pLmod/
If you want to select an item using pure javascript, you can use :
SelectOption3();
function SelectOption3() {
var sel = document.getElementById('select1');
var val = 'option3';
for(var i = 0, j = sel.options.length; i < j; ++i) {
if(sel.options[i].getAttribute("value") === val) {
sel.selectedIndex = i;
break;
}
}
}
<select id="select1">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
<option value="option5">option5</option>
</select>
You need something like this:
var test = '';
for (var i = 0; i < document.getElementById("emplStatus2").options.length; i++) {
if (document.getElementById("emplStatus2").options[i].value === 'Business') {
test = document.getElementById("emplStatus2").options[i].innerText;
}
}
alert(test);
Here is JsFiddle of your example: https://jsfiddle.net/p457utLL/

Prevent option from being disabled in the current selector

When trying to submit my form, the guard[] field doesn't submit because the options in the select fields are disabled on submit.
The code I'm working with disables the option across all selects once chosen, but I'm looking for a way to keep it enabled for the one it was selected with (i.e. if I choose "Dingo" in the first select option in the guard[] name, then the 1st select will have Dingo enabled while the 2nd and 3rd selects will have it disabled.) Code attached below.
I'm either looking for a way to get the element ID from the TagName (as seen in my code comment) or a way to re-enable the disabled option before the form is submitted.
JS/JQ:
function disableGuards(selectOption)
{
var selectedGuards = [];
var allGuards = document.getElementsByName("guard[]");
var editedSelect = selectOption.id;
for (var i = 0; i < allGuards.length; i++)
{
selectedGuards.push(allGuards[i].value);
}
for (var i = 0; i < allGuards.length; i++)
{
var options = allGuards[i].getElementsByTagName("option");
for (var o = 1; o < options.length; o++)
{
var val = options[o].value;
var chosen = selectedGuards.indexOf(val);
var myvalue = allGuards[i].value;
options[o].disabled = (chosen != -1 && val != (myvalue && "NONE") /*&& editedSelect != a way to get the elementId from TagName*/);
}
}
if (document.getElementById("guard1").value == "RAND")
{
document.getElementById("guard2").disabled = true;
document.getElementById("guard3").disabled = true;
}
else
{
document.getElementById("guard2").disabled = false;
document.getElementById("guard3").disabled = ((document.getElementById("guard2").value == "NONE") ? true : false);
}
}
HTML:
<select name='guard[]' style='width:100%' id='guard1' onChange='disableGuards(this)'>
<option selected disabled>1st Choice...</option>
<option value='RAND'>No Preferences, Please Assign an Instructor</option>
<option value='Dingo'>Dingo</option>
<option value='Mike'>Mike</option>
<option value='Stephanie'>Stephanie</option>
<option value='Zach'>Zach</option>
</select>
<br>
<select name='guard[]' style='width:100%' id='guard2' onChange='disableGuards(this)'>
<option selected disabled>2nd Choice...</option>
<option value='NONE'>No 2nd Preference</option>
<option value='Dingo'>Dingo</option>
<option value='Mike'>Mike</option>
<option value='Stephanie'>Stephanie</option>
<option value='Zach'>Zach</option>
</select>
<br>
<select name='guard[]' style='width:100%' id='guard3' onChange='disableGuards(this)'>
<option selected disabled>3rd Choice...</option>
<option value='NONE'>No 3rd Preference</option>
<option value='Dingo'>Dingo</option>
<option value='Mike'>Mike</option>
<option value='Stephanie'>Stephanie</option>
<option value='Zach'>Zach</option>
</select>
Find all options which are selected, then remove the disabled keyword
Vanilla Javascipt
document.getElementById("#testform").addEventListener("submit",function (e) {
var options = e.querySelector("option:checked"), option, i;
for(i = 0; option = options[i]; i++) {
option.removeAttribute("disabled");
}
}, false);
jQuery
$("#testform").submit(function () {
$('option:selected', this).removeProp("disabled");
});
Following code should work:
$(document).ready(function() {
$('#your-form-id').submit(function() {
$(this).find('option:disabled').prop('disabled', false);
return true;
});
});
Working fiddle here.
In your loop you could add a condition: if(selectOption !== allGuards[i]) { // disable }, which would leave the option enabled for the select that triggered the handler.
function disableGuards(selectOption)
{
var allGuards = document.getElementsByName("guard[]");
for (var i = 0; i < allGuards.length; i++)
{
if(allGuards[i] === selectOption) {
continue;
}
var options = allGuards[i].getElementsByTagName("option");
for (var o = 1; o < options.length; o++)
{
if(options[o].value === selectOption.value) {
options[o].disabled = true;
}
}
}
if (document.getElementById("guard1").value == "RAND")
{
document.getElementById("guard2").disabled = true;
document.getElementById("guard3").disabled = true;
}
else
{
document.getElementById("guard2").disabled = false;
document.getElementById("guard3").disabled = ((document.getElementById("guard2").value == "NONE") ? true : false);
}
}
<select name='guard[]' style='width:100%' id='guard1' onChange='disableGuards(this)'>
<option selected disabled>1st Choice...</option>
<option value='RAND'>No Preferences, Please Assign an Instructor</option>
<option value='Dingo'>Dingo</option>
<option value='Mike'>Mike</option>
<option value='Stephanie'>Stephanie</option>
<option value='Zach'>Zach</option>
</select>
<br>
<select name='guard[]' style='width:100%' id='guard2' onChange='disableGuards(this)'>
<option selected disabled>2nd Choice...</option>
<option value='NONE'>No 2nd Preference</option>
<option value='Dingo'>Dingo</option>
<option value='Mike'>Mike</option>
<option value='Stephanie'>Stephanie</option>
<option value='Zach'>Zach</option>
</select>
<br>
<select name='guard[]' style='width:100%' id='guard3' onChange='disableGuards(this)'>
<option selected disabled>3rd Choice...</option>
<option value='NONE'>No 3rd Preference</option>
<option value='Dingo'>Dingo</option>
<option value='Mike'>Mike</option>
<option value='Stephanie'>Stephanie</option>
<option value='Zach'>Zach</option>
</select>

Can I pass multiple Id's inside a document.getelementbyID?

I have a form which has got 45 dropdownlist and I m using the bottom code for its
validation.
how can I use only one function of bottom code to do validation for all of my 45 dropdownlist ??
Here is the Function
function Validate()
{
var e = document.getElementById("dropdownlistone");
var strUser = e.options[e.selectedIndex].value;
var strUser1 = e.options[e.selectedIndex].text;
if(strUser==0)
{
alert("Please select a user");
}
}
----- HTML CODE
<select id="dropdownlistone">
<option value="0">Select</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
<input type="button" onClick="Validate()" value="select"/>
This is a case when you need to use classes. Then use querySelectorAll method:
function Validate() {
var e = document.querySelectorAll(".dropdownlistone");
for (var i = 0; i < e.length; i++) {
var strUser = e[i].options[e[i].selectedIndex].value;
var strUser1 = e[i].options[e[i].selectedIndex].text;
if (strUser == 0) {
alert("Please select a user");
return;
}
}
}
Demo: http://jsfiddle.net/cwNaH/
And here is one more example with more user friendly validation messages: http://jsfiddle.net/cwNaH/1/
You can use DOM Method getElementsByTagName for select box and set an data-attr to "validate" for those whom you want to validate, if you dont want it to be validate simply don't add the above mentioned attribute.
Ex. HTML
<select id="sel1" data-attr="validate">
<option value="0">Select</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
<select id="sel2" data-attr="validate">
<option value="0">Select</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
JavaScript
function validate()
{
var ele = document.getElementsByTagName("select");
for(var i=0;i<ele.length;i++)
{
if(ele.getAttribute("data-attr") && ele.getAttribute("data-attr")=='validate')
{
// you have all 47 select boxes whoose data-attr is validate
// each select box will be in ele[i]
var value= ele[i].options[ele[i].selectedIndex].value;
var text= ele[i].options[ele[i].selectedIndex].text;
alert( value+ " : " + text);
}
}
}

How to store value from one dropdown list to another dropdown list

I have 2 dropdown list, where in the first dropdown list i have some data and if I select the data it has to be stored into the second dropdown list. Here is the code :-
This is the first dropdown list,
<select name="weekId" id="weekId" onchange="getSelected(value)">
<option value="Select">Select</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
<option value="Both">Both</option>
</select>
This is the second list,
<select id="selectedWeek" name="selectedWeek" size="5" multiple="multiple">
If I select Weekly in the first dropdown, the value has to get stored in the second dropdown. How do I go about implementing this?
Thanks in advance!!
var weekId = document.getElementById('weekId')
, selectedWeek = document.getElementById('selectedWeek')
, option;
weekId.onchange = function() {
option = document.createElement('option');
option.value = this.value;
option.text = this.options[this.selectedIndex].text;
selectedWeek.appendChild(option);
weekId.removeChild(this.options[this.selectedIndex]);
};​
see working fiddle here: http://jsfiddle.net/bKrFK/1/
the last line in the event-handler will remove the selected option from the weekId select-box (remove that line if not needed)
You can do this using Javascript:
function listbox_moveacross(sourceID, destID) {
var src = document.getElementById(sourceID);
var dest = document.getElementById(destID);
for(var count=0; count < src.options.length; count++) {
if(src.options[count].selected == true) {
var option = src.options[count];
var newOption = document.createElement("option");
newOption.value = option.value;
newOption.text = option.text;
newOption.selected = true;
try {
dest.add(newOption, null); //Standard
src.remove(count, null);
}catch(error) {
dest.add(newOption); // IE only
src.remove(count);
}
count--;
}
}
}
Pass this function with ids of your selectbox.
For Demo: Listbox move left-right options JavaScript
Try this..
<html>
<body>
<select name="weekId" id="weekId" onchange="document.getElementById('selectedWeek').value=this.value">
<option value="Select">Select</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
<option value="Both">Both</option>
</select>
<select id="selectedWeek" name="selectedWeek" size="5" multiple="multiple">
<option value="Select">Select</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
<option value="Both">Both</option>
</select>
</body>
</html>
Note : Second drop down has all value available in first select box.
First of all, when you call the javascript function in onChange event, replace getSelected(value) to getSelected(this.value).
Now after that,
Your javascript function getSelected(value) should look like this
function getSelected(value)
{
document.getElementById("selectedWeek").innerHTML = '<option value="'+value+'">'+value+'</option>';
}
You could use the following, without any jQuery dependencies.
I've added some comments to explain what is going on.
<script>
function handleSelection(weekDropDown) {
// Get selected value
var selection = weekDropDown.options[weekDropDown.selectedIndex].value;
var selectedWeekDropDown = document.getElementById("selectedWeek");
var opt;
if(selectedWeekDropDown.options[0]) {
// Replace
opt = selectedWeekDropDown.options[0];
} else {
// Add an option
opt = document.createElement("option");
}
if(!selectedWeekDropDown.options[0]) {
selectedWeekDropDown.options.add(opt);
}
// Set the option text and value
opt.text = selection;
opt.value = selection;
}
</script>
<select name="weekId" id="weekId" onchange="handleSelection(this)">
<option value="Select">Select</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
<option value="Both">Both</option>
</select>
<select id="selectedWeek" name="selectedWeek" size="5" multiple="multiple">

Categories

Resources