Show Current Database Value as Default in Dropdown - javascript

I have a dropdown that a selection produces another dropdown with values. All of this writes to the database correctly. I can't figure out how to show the current database value (ie the last value submitted) to show up in the 'second' drop down ('first' dropdown works fine in recalling the database information). So when I select 'Masking Available' I would like that to show up when I open the webpage next time.
function configureDropDownLists(main, second) {
var masking1e = new Array('', 'Masking Available');
var permissivemode1e = new Array('', 'Permissive Mode Enabled');
switch (main.value) {
case 'Masking':
document.getElementById(second).options.length = 0;
for (i = 0; i < masking1e.length; i++) {
createOption(document.getElementById(second), masking1e[i], masking1e[i]);
}
break;
case 'Permissive Mode':
document.getElementById(second).options.length = 0;
for (i = 0; i < permissivemode1e.length; i++) {
createOption(document.getElementById(second), permissivemode1e[i], permissivemode1e[i]);
}
break;
default:
document.getElementById(second).options.length = 0;
break;
}
}
function createOption(first, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
first.options.add(opt);
}
<select name="first" id="first" onchange="configureDropDownLists(this,'second')">
<option value="">Please Select Accommodation</option>
<option value="Masking" <?php if ($first== "Masking"){ echo "SELECTED"; } ?>>Masking</option>
<option value="Permissive Mode" <?php if ($first== "Permissive Mode"){ echo "SELECTED"; } ?>>Permissive Mode</option>
</select>
</br>
<select name="second" id="second">
</select>

Related

Copy selected multiple values to the textbox from more than one drop down

I have tow drop downs as below.
<select id="checkOwner" multiple="multiple" onchange="copyValue1(this)">
<option value="FirstName">First Name</option>
<option value="SecondName">Last Name</option>
</select>
<select id="checkMember" multiple="multiple" onchange="copyValue2(this)>
<option value="FirstName">First Name</option>
<option value="SecondName">Last Name</option>
</select>
I have below javascript to print selected multiple values from dropdowns.
function copyValue() {
var str = "";
for (var option of document.getElementById('checkOwner').options) {
if (option.selected) {
str+= option.value+" ";
}
document.getElementById('mytextbox').value = str;
}
}
function copyValue2() {
var str = "";
for (var option of document.getElementById('checkMember').options) {
if (option.selected) {
str+= option.value+" ";
}
document.getElementById('mytextbox').value = str;
}
}
The problem is when I select values from first that value print in text box. But I select value from second dropdown First printed values disappeared and second dropdown box values are printed. But I want to keep all and when I untick I want to remove this value also. How can I do this.
If you accepting duplicate values then, this is the solution:
I updated your HTML code to suit your needs by adding real values to your dropdown lists instead of using "FirstName,LastName".
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<select id="checkOwner" multiple="multiple" onchange="copyValue()">
<option value="John">John</option>
<option value="Abeer">Abeer</option>
</select>
<br>
<select id="checkMember" multiple="multiple" onchange="copyValue2()">
<option value="Doe">Doe</option>
<option value="Trump">Trump</option>
<option value="Abeer">Abeer</option>
</select>
<br>
<input type="text" name="mytextbox" id="mytextbox" size="200">
</body>
<script type="text/javascript">
function getOld(currentSelect)
{
var x = [];
for (var option of document.getElementById(currentSelect).options) {
if (option.selected) {
x.push(option.value);
}
}
return x;
}
function copyValue() {
x = getOld('checkMember');
y = [];
for (var option of document.getElementById('checkOwner').options) {
if (option.selected) {
y.push(option.value);
}
else
{
y = y.filter(value => value != option.value );
}
}
x = x.concat(y);
document.getElementById('mytextbox').value = x.join(' ');
}
function copyValue2() {
x = getOld('checkOwner');
y = [];
for (var option of document.getElementById('checkMember').options) {
if (option.selected) {
y.push(option.value);
}
else
{
y = y.filter(value => value != option.value );
}
}
x = x.concat(y);
document.getElementById('mytextbox').value = x.join(' ');
}
</script>
</html>

Refreshing select2 drop down list

I'm trying to dynamically change the option of a select2 dropdown.
I've searched the forum and have managed to change the selected option, but it is only visible when clicking on the dropdown and seeing the entire list. Apologies in advance for not being the best coder.
function changeSelectOption(designSelVal) //designSelVal = 9
{
var opts = document.getElementById("design").options;
for (var opt, i = 0; opt = opts[i]; i++)
{
if (opt.value == design)
{
document.getElementById("design").selectedIndex = i;
break;
}
}
}
/* this shows as having correctly changed from value 2 to 9 */
<option value="2" >Text Only</option>
<option value="4" >Heart Arrow</option>
<option value="9" selected>Heart</option>
The visible option remains 'Text Only' and not 'Heart', it's as if the select box needs refreshing.
You are missing the if condition :
it should be
if (opt.value == designSelVal)
function changeSelectOption(designSelVal) //designSelVal = 9
{
var opts = document.getElementById("design").options;
for (var opt, i = 0; opt = opts[i]; i++) {
if (opt.value == designSelVal) {
document.getElementById("design").selectedIndex = i;
break;
}
}
}
changeSelectOption(9);
<select id="design">
<option value="2" selected>Text Only</option>
<option value="4">Heart Arrow</option>
<option value="9" >Heart</option>
</select>

How to add search filter in populating select dropdown

I have 2 Select dropdown in which value of 1 dropdown based on the first dropdown. Now I want to add search filter in second populating dropdown. How I achieve this? I used many plugins for search filter like SOL but it did not work. Please help. Below is my code..
HTML
<select name="industry" id="industry" class="industry" style="width:305px;" onchange="configureDropDownLists(this,document.getElementById('product_type')); func2();" required>
<option value="" disabled="disabled" selected>Choose Industry*</option>
<option value="Agriculture & Food">Agriculture & Food</option>
<option value="Apparel, Textiles & Accessories">Apparel, Textiles & Accessories</option>
<option value="Auto & Tranportation">Auto & Tranportation</option>
<option value="Bags, Shoes & Accessories">Bags, Shoes & Accessories</option>
<option value="Electronics">Electronics</option>
<option value="Gifts, Sports & Toys">Gifts, Sports & Toys</option>
</select>
<select name="product_type" id="product_type" style="width:305px;">
</select>
Javascript
function configureDropDownLists(ddl1,ddl2) {
var AgricultureFood = ['Agricultural Growing Media', 'Agricultural Waste', 'Animal Products', 'Beans'];
var ApparelTextilesAccessories = ['Apparel Design Services', 'Apparel Processing Services', 'Apparel Stock'];
switch (ddl1.value) {
case 'Agriculture & Food':
ddl2.options.length = 0;
for (i = 0; i < AgricultureFood.length; i++) {
createOption(ddl2, AgricultureFood[i], AgricultureFood[i]);
}
break;
case 'Apparel, Textiles & Accessories':
ddl2.options.length = 0;
for (i = 0; i < ApparelTextilesAccessories.length; i++) {
createOption(ddl2, ApparelTextilesAccessories[i], ApparelTextilesAccessories[i]);
}
break;
default:
ddl2.options.length = 0;
break;
}
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
Now I want to add search filter in 2nd Select dropdown (Id=product_type) . Thanks in advance.
You can achieve your goal by implementation of jQuery multiselect plugin.
Here is the sample code.You just need to call this function after dropdown creation complete.
<!--css for multiselect-->
<link href="css/jquery.multiselect.css" rel="stylesheet" />
<link href="css/jquery.multiselect.filter.css" rel="stylesheet" />
<!--JS for multiselect-->
<script src="js/jquery.multiselect.js"></script>
<script src="js/jquery.multiselect.filter.js"></script>
<script type="text/javascript>
//Initialize first-time when dropdown created or on page load.
jQuery("#product_type").multiselect({
minWidth: 360, multiple: false,
selectedList: 1
}).multiselectfilter({width:250});
function configureDropDownLists(ddl1,ddl2) {
var AgricultureFood = ['Agricultural Growing Media', 'Agricultural Waste', 'Animal Products', 'Beans'];
var ApparelTextilesAccessories = ['Apparel Design Services', 'Apparel Processing Services', 'Apparel Stock'];
switch (ddl1.value) {
case 'Agriculture & Food':
ddl2.options.length = 0;
for (i = 0; i < AgricultureFood.length; i++) {
createOption(ddl2, AgricultureFood[i], AgricultureFood[i]);
}
break;
case 'Apparel, Textiles & Accessories':
ddl2.options.length = 0;
for (i = 0; i < ApparelTextilesAccessories.length; i++) {
createOption(ddl2, ApparelTextilesAccessories[i], ApparelTextilesAccessories[i]);
}
break;
default:
ddl2.options.length = 0;
break;
}
jQuery('#product_type').multiselect('refresh');
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
</script>
http://www.erichynds.com/examples/jquery-ui-multiselect-widget/demos/#filter
http://www.erichynds.com/examples/jquery-ui-multiselect-widget/demos/#refresh

JavaScript - how to keep last submitted value in select box (dynamically generated select box)

can you please help(or point me to right direction) in order to modify following code? I would like to keep value in second selection box (id="detail") once the form is submitted. As you can see, the second box is dynamically generated via JavaScript.
thank you ..
<form method="get" action="index.php">
<script>
function configureDropDownLists(aa,detail) {
var colours = ['red', 'green'];
var cars = ['audi', 'fiat'];
switch (aa.value) {
case 'colours':
detail.options.length = 0;
for (i = 0; i < colours.length; i++) {
createOption(detail, colours[i], colours[i]);
}
break;
case 'cars':
detail.options.length = 0;
for (i = 0; i < cars.length; i++) {
createOption(detail, cars[i], cars[i]);
}
break;
default:
detail.options.length = 0;
break;
}
}
function createOption(object, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
object.options.add(opt);
}
</script>
<select id="object" name="objects" onchange="configureDropDownLists(this,document.getElementById('detail'))">
<option value=""></option>
<option <?php if ($_GET['objects'] == 'colours') { ?>selected="true" <?php }; ?>value="colours">colours</option>
<option <?php if ($_GET['objects'] == 'cars') { ?>selected="true" <?php }; ?>value="cars">cars</option>
</select>
<select id="detail">
</select>
<input type="submit" value="Submit" class="submit" />
</form>
Since you are generating the options dynamically, the options don't even exist after the form is submitted. So I think you should call the function once when the page loads to create them.
Also, you have to give the function that is creating the options the default value that it should set as selected.
Here are the changes I would recommend:
<form method="get" action="index.php">
<script>
function configureDropDownLists(aa,detail,selected) {
//alert(selected);
var colours = ['red', 'green'];
var cars = ['audi', 'fiat'];
switch (aa.value) {
case 'colours':
detail.options.length = 0;
for (i = 0; i < colours.length; i++) {
createOption(detail, colours[i], colours[i], selected);
}
break;
case 'cars':
detail.options.length = 0;
for (i = 0; i < cars.length; i++) {
createOption(detail, cars[i], cars[i], selected);
}
break;
default:
detail.options.length = 0;
break;
}
}
function createOption(object, text, value, selected) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
opt.selected = (selected == value) ? "selected" : '';
object.options.add(opt);
}
</script>
<select id="object" name="objects" onchange="configureDropDownLists(this,document.getElementById('detail'),'<?php echo isset($_GET['detail']) ? $_GET['detail'] : ''; ?>')">
<option value=""></option>
<option <?php if ($_GET['objects'] == 'colours') { ?>selected="true" <?php }; ?>value="colours">colours</option>
<option <?php if ($_GET['objects'] == 'cars') { ?>selected="true" <?php }; ?>value="cars">cars</option>
</select>
<select id="detail" name="detail">
</select>
<input type="submit" value="Submit" class="submit" />
</form>
<script>
configureDropDownLists(document.getElementById('object'),document.getElementById('detail'),'<?php echo isset($_GET['detail']) ? $_GET['detail'] : ''; ?>')
</script>
Notice the two changes I made. I called the configureDropDownLists function at the bottom to dynamically create the options when the page load. And I passed the $_GET['detail'] variable to the function to set it as the default.

How to create a select that depends on the value of another select?

I need to create a menu of regions hat display two lists: a <select> for the region and another <select> for the available municipalities of that region. For this, I have a <form> and I update the municipalities through JavaScript. I have problems assigning the municipalities as <option>s of the second <select>. The option matrix of the menu doesn't accept the assignment of the values.
Here's the code.
HTML.
<html>
<head>
<title>
Página menú principal.
</title>
<?!= incluirArchivo('ArchivoJS'); ?>
</head>
<body onLoad = "preparar();">
<form id="formularioConductor" name="formularioConductor" method="post" enctype="multipart/form-data" autocomplete = "on">
<select name="menuDepartamento" id="menuDepartamento" tabindex="2" accesskey="e" onChange="municipiosDepartamento();">
<option value="x" selected="selected">ELIJA UN DEPARTAMENTO</option>
<option value="0">Antioquia</option>
<option value="1">Atlántico</option>
</select>
<select name="menuMunicipios" id="menuMunicipios" tabindex="3" disabled>
<option value=0>TODOS LOS MUNICIPIOS</option>
</select>
</form>
</body>
</html>
Javascript code:
<script lenguage="javascript">
function preparar() {
document.forms[0].elements.numeroLicencia.focus();
document.forms[0].elements.nombreConductor.disabled = true;
document.forms[0].elements.botonEnviar.disabled = true;
document.forms[0].elements.botonActualizar.disabled = true;
}
function municipiosDepartamento() {
var arregloMunicipiosDepartamento = new Array();
var posicionMunicipio = document.forms[0].elements.menuDepartamento.value;
arregloMunicipiosDepartamento = municipiosColombia(posicionMunicipio);
if(document.forms[0].elements.menuMunicipios.options.length > 1){
var totalMunicipios = document.forms[0].elements.menuMunicipios.length;
for (var i = 1; i < totalMunicipios; i ++){
document.forms[0].elements.menuMunicipios.options[1] = null;
}
}
if(document.forms[0].elements.menuDepartamento.value === "x"){
document.forms[0].elements.menuMunicipios.selectedItem = 0;
document.forms[0].elements.menuMunicipios.disabled = true;
}
else
{
document.forms[0].elements.menuMunicipios.options.length = arregloMunicipiosDepartamento.length;
for (var i = 0; i < arregloMunicipiosDepartamento.length; i ++) {
var opcionTemporal = new Option(arregloMunicipiosDepartamento[i], (i+1));
***document.forms[0].elements.menuMunicipios.options[i+1].text = opcionTemporal.text;
document.forms[0].elements.menuMunicipios.options[i+1].value = opcionTemporal.value;***
}
document.forms[0].elements.menuMunicipios.disabled = false;
}
}
function municipiosColombia(posicion) {
var antioquia, atlantico, arregloTodos, arregloMunicipiosDepartamento = new Array();
antioquia=["Medellín","Abejorral","Abriaqui","Alejandria"];
atlantico = ["Barranquilla","Baranoa","Campo De La Cruz","Candelaria"];
arregloTodos = [antioquia, atlantico];
arregloMunicipiosDepartamento=arregloTodos[posicion];
return arregloMunicipiosDepartamento;
}
</script>
I have highlighted the work that doesn't work.
The way I would do what you describe is to clear out the options each time and recreate the required ones, then add them into the particular select, like so:
var regions = {};
regions['A'] = ['mu', 'ni', 'ci', 'pal', 'it', 'y'];
regions['B'] = ['I', 'like', 'bananas'];
var selRegion = document.getElementById('region');
selRegion.onchange = setMunicipalities;
var selMun = document.getElementById('municipality');
function setMunicipalities(e)
{
while(selMun.length > 0)
{
selMun.remove(0);
}
if(selRegion.selectedOptions[0].value === 'ALL')
{
for(var r in regions)
{
if(regions.hasOwnProperty(r))
{
addMunicipalities(regions[r]);
}
}
}
else
{
var reg = selRegion.selectedOptions[0].value;
addMunicipalities(regions[reg]);
}
}
function addMunicipalities(region)
{
var allMun = document.createElement('option');
allMun.setAttribute('value', 'ALL');
var allMunText = document.createTextNode('ALL');
allMun.appendChild(allMunText);
selMun.add(allMun);
for (var mi = 0; mi < region.length; mi++)
{
var m = region[mi];
var mun = document.createElement('option');
mun.setAttribute('value', m);
var munText = document.createTextNode(m);
mun.appendChild(munText);
selMun.add(mun);
}
}
setMunicipalities(null);
<label for="region">Region</label>
<select id="region">
<option selected="selected" value="ALL">ALL</option>
<option value="A">A</option>
<option value="B">B</option>
</select>
<label for="municipality">Municipality</label>
<select id="municipality">
</select>
I haven't read your entire code because I had a hard time reading code with contents not in English but anyway, I get what you're trying to do here. Suppose that your first select list contains "Region A" and "Region B" as options; "Municipality A1", "Municipality A2", "Municipality B1","Municipality B2" are the possible options for the second select list. Here's a function that will change the options of the second select list depending on what is selected on the first select list:
function optionChanger(v_selected){
var whatisselected= v_selected.options[v_selected.selectedIndex].value;
var municipalities= {};
municipalities['A'] = ['Municipality A1','Municipality A2'];
municipalities['B'] = ['Municipality B1','Municipality B2'];
v_selected.options.length=0; //remove the contents of the second select list
v_selected.options[0] = new Option(municipalities[whatisselected][0],municipalities[whatisselected][0],false,true);// set the first option of the second list as the default selected value
for(x=1;x<municipalities[whatisselected].length;x++){ //add the remaining options to the second list
v_selected.options[x] = new Option(municipalities[whatisselected][x],municipalities[whatisselected][x],false,false);
}
}
Then add this inside the tag of your FIRST select list:
onchange='optionChanger(this)'
PS: Please notice that the return value of the first select list must be 'A', 'B'

Categories