I'm setting 2 select in html, the second one depends of the first one, so I use a script "onchange", so when the first value of the select change, the second one change too, I don't know how to get the variable of my FOR to get the index of the thymeleaf model in my script
SCRIPT-
So my problem here it's inside the if when I tried to get the value of documentos[i].proyecto.id, but I can get documentos[0, 1 or any number].proyecto.id
/*<![CDATA[*/
function load(){
var e = document.getElementById("proyecto-id");
var value = e.options[e.selectedIndex].value;
var sub = document.getElementById("documento-id");
var length = sub.options.length;
for (z = 0; z < length; z++) {
sub.options[z] = null;
}
for(i=0;i<[[${#lists.size(documentos)}]];i++){
if([[${documentos[ i ].proyecto.id}]] == value){
var opt = document.createElement('option');
opt.value = [[${documentos[ i ].id}]]
opt.text = [[${documentos[ i ].nombre}]];
sub.add(opt);
}
}
}
/*]]>*/
HTML select
<select id="proyecto-id" class="custom-select" th:onchange="load()">
<option th:each="p : ${proyectos}"
th:text="${p.nombre}"
th:value="${p.id}">
</option>
</select>
<select id="documento-id" class="custom-select">
</select>
Related
I have a Google sheet with custom HTML form. The form contains <selection> element.
Like this
<select id="category_name" name="category_name" class="control" style="width:150px;height:20px;margin:10px 0 10px 0;">
<option value="" selected></option>
</select>
I'm getting values from the sheet
function getCategory() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sh = ss.getSheetByName(SHEET_NAME);
let list = sh.getRange(2, 1, sh.getLastRow() - 1).getValues();
return list;
}
And then I'm populating this selection with expected values in HTML file
(function () {
google.script.run.withSuccessHandler(
function (selectList) {
var select = document.getElementById("category_name");
for( var i=0; i<selectList.length; i++ ) {
var option = document.createElement("option");
option.val = selectList[i][0];
option.text = selectList[i][0];
select.add(option);
}
}
).getCategory();
}());
It looks like list was populated well, but when I choice some item from selection it returns blank value after form submitting.
Where I'm wrong and how to fix it?
Issue:
You are not setting the <option> value correctly: val is not a valid attribute. Because of this, no value is added to each <option> and they are not submitted.
Solution:
Set the option value like this:
option.value = selectList[i][0];
Using Option constructor:
Of course, using the Option constructor would also work:
var option = new Option(selectList[i][0], selectList[i][0]);
Reference:
HTMLOptionElement
Option()
I use this a lot:
function updateSelect(vA,id){
var id=id || 'sel1';
var select = document.getElementById(id);
select.options.length = 0;
for(var i=0;i<vA.length;i++) {
select.options[i] = new Option(vA[i],vA[i]);//Option(text, value);
}
}
new option
I created a function which contains a string that I want to add to a in HTML. But when I test it, it won't show me the options declared in my table.
function test(){
// table already defined
var choices = "<option selected>Select...</option>";
for (var i=0; i<tableOptions.length; i++) {
choices += "<option>" + tableOptions[i][0] +"</option>";
}
document.getElementById("theOptions").innerHTML = choices;
}
and in my HTML I have
<select id="theOptions"></select>
What am I doing wrong?
By the way, my test() is automatically loaded after my page is displayed.
<body onload="test()">
See How to populate the options of a select element in javascript for detail on creating and appending options to an existing <select> element.
Using that method, this seems closest to what you're getting at:
var select = document.getElementById("theOptions");
opt = document.createElement("option");
opt.innerHTML = "Select...";
select.appendChild(opt);
for(var i = 0; i < tableOptions.length; i++)
{
var opt = document.createElement("option");
opt.innerHTML = tableOptions[i][0];
select.appendChild(opt);
}
I want to create a dynamic drop down list with javascript.
Right now it works like this:
- if I choose first option, then second, then third.
I want to change this code to:
- when I choose first option, it shows second and third option in the same time(second and third option depends of first)
I want to do something like:
Choose name:
John Doe(first option)
Choose proffesion:
Dentist(second option)
Choose gender:
male(third option)
Is it possible?
Thanks for reply.
<!doctype html>
<html>
<head>
<script>
var modelsArray = new Array(
["Chevy","","Camaro","Corvette","Impala"],
["Dodge","","Avenger","Challenger","Charger"],
["Ford","","Mustang","Shelby"]
);
var colorsArray = new Array(
["Camaro","","White","Black","Red"],
["Corvette","","White","Purple","Blue","Fawn"],
["Impala","","White","Black","Red","Chrome Yellow"],
["Avenger","","White","Acid Green","Alice Blue"],
["Challenger","","White","Violet","Blue-Green"],
["Charger","","White","Dark Pastel Red"],
["Mustang","","White","Debian red","Impala","Flame"],
["Shelby","","White","Deep Spring Bud"]
);
function populate1(s1,s2,s3){
var optionArray = [];
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
var s3 = document.getElementById(s3);
s3.innerHTML = "";
for(var i = 0; i < modelsArray.length; i++){
if(s1.value == modelsArray[i][0]){
for(var x = 1; x < modelsArray[i].length; x++){
optionArray.push(modelsArray[i][x]);
}
}
}
optionArray.sort();
for(var option in optionArray){
var newOption = document.createElement("option");
newOption.value = optionArray[option];
newOption.innerHTML = optionArray[option];
s2.options.add(newOption);
}
}
function populate2(s1,s2){
var optionArray = [];
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
for(var i = 0; i < colorsArray.length; i++){
if(s1.value == colorsArray[i][0]){
for(var x = 1; x < colorsArray[i].length; x++){
optionArray.push(colorsArray[i][x]);
}
}
}
optionArray.sort();
for(var option in optionArray){
var newOption = document.createElement("option");
newOption.value = optionArray[option];
newOption.innerHTML = optionArray[option];
s2.options.add(newOption);
}
}
</script>
</head>
<body>
<h2>Choose Your Car</h2>
<hr />
Choose Car Make:
<select id="slct1" name="slct1" onchange="populate1(this.id,'slct2','slct3')">
<option value=""></option>
<option value="Chevy">Chevy</option>
<option value="Dodge">Dodge</option>
<option value="Ford">Ford</option>
</select>
<hr />
Choose Car Model:
<select id="slct2" name="slct2" onchange="populate2(this.id,'slct3')"></select>
<hr />
Choose Car Color:
<select id="slct3" name="slct3"></select>
<hr />
</body>
</html>
I've created a jsfiddle here which implements a rudimentary example.
You can create DOM event listeners to respond to the change event of the select elements. When these events are triggered, pass the value of the selected option to a function which can extract the models/colours from the data.
Ideally you will setup your server side code to return the data in a format such as:
{
"makes": {
"ford": {
"models": {
"focus": {
"colours": [
"blue",
"black"
]
},
"probe": {
"colours": [
"green",
"grey"
]
}
}
}
}
Using this data format you can easily drill down the object tree e.g.
carData.makes.ford.models.focus.colours
Once you have the data you can then use jQuery to append options to your select e.g.
for (var model in models) {
$('select').append('<option value="'
+ model + '">' + model +
'</option>');
}
*EDIT: If you want to use the combination of the first two selects then you can do something like this:
var mapCombinations = {canada: {toronto: {mapName: "canada"}}};
var mapName = mapCombinations[selectValue1][selectValue2].mapName);
showMap(mapName);
function showMap(mapName) {
// Call server to get map
$.ajax({
type: "GET",
url: "http://yoururl.com/api/map/" + mapName,
success: function(data){
// display map
}
});
}
EDIT2: You can use the same principle if you want the third select to contain an action. I've replaced the colours array with actions. This third select will change depending on the first 2 select values.
Updated jsfiddle which doesn't use jquery.
You can then set up an event listener to process that action.
I need to repeat third value all the time.
I try to give you an example.
First value = Country
Second value = City
Third value = option
And I want to do something like:
If First value = Canada then Second value = Toronto
If First value = Canada then Third value = Show canada map
Second Value and third value don't depend of themselve, only of first value.
I am trying to load the first available option to the third drop-down.
The code is as below.
var categories = [];
categories["startList"] = ["C.","C#.","D.","Eb.","E.","F.","F#.","G.","Ab.","A.","Bb.","B."]; // Level 1
categories["C."] = ["C","C7","Cm","Cm7","Cmaj7","Csus4","Caug","Cdim"];
categories["C"] = ["032010","335553","133211","543210",""];
var nLists = 3; // number of lists in the set
function fillSelect(currCat,currList){
var step = Number(currList.name.replace(/\D/g,""));
for (i=step; i<nLists+1; i++) {
document.forms[0]['List'+i].length = 1;
document.forms[0]['List'+i].selectedIndex = 0;
}
var nCat = categories[currCat];
for (each in nCat) {
var nOption = document.createElement('option');
var nData = document.createTextNode(nCat[each]);
nOption.setAttribute('value',nCat[each]);
nOption.appendChild(nData);
currList.appendChild(nOption);
}
}
function init() { fillSelect('startList',document.forms[0]['List1']);
fillSelect('startList',document.forms[0]['List4']);
fillSelect('startList',document.forms[0]['List7']);
}
navigator.appName == "Microsoft Internet Explorer"
? attachEvent('onload', init, false)
: addEventListener('load', init, false);
function getValues() {
var str = '';
for(i = 1; i < 6; i++) {
document.createElement('select')
str += document.getElementById('List' + i).value+'\n';
document.getElementById('creation').innerHTML=""; }
}
<select name='List4' id="List4" onchange="fillSelect(this.value,this.form['ch2'])"><option selected></option></select>
<select name='ch2' id="ch2" onchange="fillSelect(this.value,this.form['tb2'])"><option selected></option></select>
<select name='tb2' id="tb2"><option selected></option></select>
<input id="f2" type="text" size="1" value=1 class=copystuff>
<button onclick="do2()">Do2</button><br>
Now the problem is that when I try to select the second drop down menu "ch2", I want the first value to be loaded automatically in the third dropdown "tb2" according to the selection that I make in the second menu. For eg, if I select C. in the first menu, C in the second menu, I want 032010 to be already selected in the next menu. Is there any simple way to do this?
I have changed your code up a good bit. But I think it's a bit more readable, and may be easier to extend to more forms, categories, and selects.
First here is the working JSFiddle: http://jsfiddle.net/z1sw2bfq/
Second, here is the Fiddle code. Please see the comments for additional context.
<script>
//create a blank object to hold the select lists
var lists = { };
//create an object to hold the categories text arrays
var categories = {
"startList": ["C.","C#.","D.","Eb.","E.","F.","F#.","G.","Ab.","A.","Bb.","B."], // Level 1
"C.": ["C","C7","Cm","Cm7","Cmaj7","Csus4","Caug","Cdim"],
"C": ["032010","335553","133211","543210",""]
};
function init() {
//load the SELECT element from the form into lists
//Get all of the selects in forms[0]...
var selects = document.forms[0].getElementsByTagName("select");
for (var i in selects) {
//...and load those into lists.
lists[selects[i].id] = selects[i];
//Ex: creates a property like "lists.List4" also referenced by "list['List4']")
// which equals the select element with id List4
}
//enter the list name and the select id
fillSelect('startList', 'List4');
}
function fillSelect(currCatName, currListName){
//get the category
var cat = categories[currCatName];
//verify the category is valid
if (cat) {
//get the select
var select = lists[currListName];
//verify the select is valid
if (select) {
//clear the select
for (var i = select.options.length-1; i>=0; i--)
select.remove(i);
//check the data-first attribute
var datafirst = select.getAttribute("data-first");
if (datafirst == "blank") {
var opt = document.createElement('option');
opt.value = "";
opt.text = "";
select.add(opt);
}
//load the select
for (var j in cat) {
var opt = document.createElement('option');
opt.value = cat[j];
opt.text = cat[j];
select.add(opt);
}
}
}
}
//best to use feature detection instead of browser detection
if (window.attachEvent)
window.attachEvent('onload', init, false);
else
window.addEventListener('load', init, false);
</script>
<form action="#" method="get">
<!--
I added a "data-first" attribute to the selects. This will be used to determine if the
first option in the select is a blank or the first item in the list.
-->
<select name='List4' id="List4" onchange="fillSelect(this.value,'ch2')" data-first="blank"></select>
<select name='ch2' id="ch2" onchange="fillSelect(this.value,'tb2')" data-first="blank"></select>
<select name='tb2' id="tb2" data-first="first"></select>
</form>
my html code.
<input type="button" onClick="show($row['empDesignation']?>');" value="update"/>
so when i click on update button m passing the value to javascript
<script type="text/javascript">
function show(desig){
document.getElementById("designation").value=desig;
}
</script>
so i want the value which is passed to javacript to be listed first in the dropdown list
php code
<select id="designation" name="designation">
<? while($role=mysql_fetch_array($sql_role)){ ?>
<option value="<?=$role['id']?>"><?=$role['id']?></option>
<? } ?></select>
<option value="<?php echo $role['id']?>"><?php echo $role['id']?></option>
You can do that like following algorithm;
Get your entire select options and put it in to array
Remove all options from selectbox
Put first option that you get from show function
Fill rest of the item from array to selectbox.
You can see an example below;
function show(desig) {
var arr = [];
var list = document.getElementById("designation");
for (var i = 0; i < list.options.length; i++) {
arr.push(list.options[i]);
}
// Delete all options from selectbox
list.options.length = 0;
// create first option
var opt = document.createElement('option');
opt.innerHTML = desig;
opt.value = desig;
list.appendChild(opt);
for (var j in arr) {
if (arr[j].value !== desig) {
var opt = document.createElement('option');
opt.innerHTML = arr[j].text;
opt.value = arr[j].value;
list.appendChild(opt);
}
}
}
You can see working demo here: http://jsfiddle.net/rZmgY/1/