how to make dropdown selected when running dynamically - javascript

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/

Related

How to populate dropdown list at selection element with values from Google sheet?

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

Javascript iteration with thymeleaf, how to pass index to array in thymeleaf

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>

fill a <select> with a function Javascript

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);
}

Automatically Load the option to drop down menu

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>

How to create a dynamic SELECT drop-down list in JavaScript/jQuery?

I want to display the all the department names in the Dept Table in a combo box.
I have a function which fetches all the Dept name.
How can I dynamically create combo box in runtime, using javaScript or jQuery.
HTML CODE
<select id="searchDepartments">
</select> <input type="button" value="Search" onClick="search();" />
JavaScript function
function getDepartments(){
EmployeeManagement.getDeptList(function(deptList/*contains n-(dept.id, dept.name)*/{
for(i = 0; i<deptList.length; i++){
How can I able to write a code that generates(adds) options to the list?
The process is to create an option node for each item in the list, and add it as a child of the select element.
In plain javascript:
var sel = document.getElementById('searchDepartments');
var opt = null;
for(i = 0; i<deptList.length; i++) {
opt = document.createElement('option');
opt.value = deptList[i].id;
opt.innerHTML = deptList[i].name;
sel.appendChild(opt);
}
There's a plugin that already does this, you may want to check it out. Another benefit of this plugin, is that it has autocomplete built in.
A drop-down combo box, or a select box
into which you can type text to narrow
down the visible result set. This code
is a compilation of the JQuery
Autocomplete plugin as well as other
JQuery plugins, and is still in the
alpha stage of development.
A plain and simple JavaScript script would look as follows:
function AddOption(comboBoxID, displayText, displayValue)
{
var optionItem = document.createElement("option");
optionItem.text = displayText;
optionItem.value = displayValue;
document.getElementById(comboBoxID).options.add(optionItem);
}
You can use the following generic function:
function addOption(text,value,cmbId) {
var newOption = new Option(text, value);
var lst = document.getElementById(cmbId);
if (lst) lst.options[lst.options.length] = newOption;
}
You can create a datalist new option in html5:
<input type="text" class="form-control" id="your_id" list="your_list"
placeholder="Status"/>
<datalist id="your_list">
</datalist>
and fill it with a jquery .append function:
for(var i=0, len=resultado.response['id'].length; i<len; i++)
{
list += '<option value="' +resultado.response['data'][i]+" ( "+resultado.response['id'][i]+" ) "+ '"></option>';
}
dataList.html(list);

Categories

Resources