Two Select Drop down boxes, the first updates the second NO AJAX - javascript

I need two drop down form boxes. Selecting content in the first one updates the second one.
However I do not want to use AJAX JSON updating in the Javascript (I've found these online but can't get them working on my server). What I would rather do is generate a list when the page loads and have the Javascript pull from a list already loaded on the page. The data is coming from a mySQL database but since it is preloaded on the page its faster.
I can handle getting the data from the database but what I need is the JS that changes the for the second drop down box getting the data from a variable list or some other function rather then a AJAX JSON update.
I'll use jquery if I can but all I find online is AJAX versions of this script.

<select id="firstselect" onchange="changeMe(id)" />
<script>
function changeMe(id) {
var options1=[1,2,3,4];
var options2=[2,3,4,5];
var options = null;
if (id = 1) {
var options = options1;
} else {
var options = options2;
}
for (var i = 0; i < options.length; i++) {
var optn = document.createElement("OPTION");
optn.text = options[i];
optn.value = options[i];
$('secondSelect').add(option, i);
}
}
</script>

Related

Why auto complete does not work in this example with Bootstrap?

I am trying to implement an auto complete dropdown with dynamic data but it doesnt display any suggestions in the dropdown. I am using this example - Datalists: https://getbootstrap.com/docs/5.1/forms/form-control/
which works fine with predefined option tags.
<label for="exampleDataList" class="form-label">Datalist example</label>
<input class="form-control" list="datalistOptions" id="exampleDataList" placeholder="Type to search...">
<datalist id="datalistOptions">
... dynamic data here
</datalist>
I do receive data from the PHP script and they are correctly accessed but I think the problem might be due to the delay of the fetch. HTML might expect the data to already be there when loaded. That's why maybe it works with existing data.
here is the javacsript code inside the fetch function where I dynamically produce the tags:
var select = document.getElementById("datalistOptions");
select.innerHTML = "";
for (var key in data['result']) {
var val = data['result'][key];
if (data['result'].hasOwnProperty(key) && key != "error") {
var val = data['result'][key];
if (val != "") {
var option = document.createElement("option");
option.value = val.id;
select.appendChild(option);
}
}
}
Update: I changed the js code a bit. Now it uses appendChild instead of add function. The previous one was not adding any options to the datalist. appendChild does add options to the list but it does not display them.
This is a simpler version of what you trying to do.
Try to take it, add your conditions, and make that data come in that form if you can.
var data = ["Haifa","Tel Aviv","Jerusalem"];
var select = document.getElementById("datalistOptions");
select.innerHTML = "";
for (var key in data) {
var option = document.createElement("option");
option.label = data[key];
option.value = data[key];
select.appendChild(option);
}
And make sure you adds onclick event that calls you script, maybe this is you problem, that you not calling the script - I would recomand somethig like that:
<input onclick="datalistCreate()" class="form-control" list="datalistOptions" id="exampleDataList" placeholder="Type to search...">
datalistCreate() is the function name in the script.

dynamic dropdown for file selection

I am trying to tweak an existing .html file to add a feature. I am very new to the frontend dev env.
<form action="javascript:void(0);">
<input type="button" name="Load" value="Load" onclick="fileLoad();"/>
<input type="button" name="showFiles" value="Select File" onclick="selectFiles();"/>
</form>
I would like to have a dropdown (dynamic list). Which occurs when i click the button "Select File". I have tried to use the selectFiles() function to achieve this. Eventhough, I can get the list of files from backend. How can i display it on the frontend
Once you get your list from the server you can do,
function makeList(fileNames) {
// create a container for the select in your html
var myDiv = document.getElementById("myDiv");
// Create and append select list
var selectList = document.createElement("select");
selectList.id = "filesSelect";
myDiv.appendChild(selectList);
// Create and append the options
for (var i = 0; i < fileNames.length; i++) {
var option = document.createElement("option");
option.value = fileNames[i]; // this will depend on the datastructure of your list items
option.text = fileNames[i]; // this will depend on the datastructure of your list items
selectList.appendChild(option);
}
}
This function should go as a callback to your server call.
I have not tested it, but it should give you a clear idea.

Array not being filled when the HTML page loads

I am working on a project using Google Apps Script coupled with HTML and JS. I am fairly new to programming, so bear with me if this is a simple question.
Basically, in my JS file I have a function that calls a function contained in the Google Apps Script (from now on, GAS) file using this method; the GAS function populates an array with values retrieved from a Google Sheets and returns the array. This array is then used by the JS file to populate a drop down list in the HTML file.
The issue is that the dropdown list is not populated at all; if I reload the page with the Google Chrome console on, I see that the array is empty; however, if I click on the empty array, the values are shown, as if it is not populated on page load. See the picture below to have a better understanding of what I mean:
Google Chrome Console screenshot
Below you'll find the relevant snippets of code that handle the differente functions:
JS:
$(function() {
var cities = [];
function onSuccess(elem, array) {
var i = 0;
for (item in elem) {
array.push(elem[i])
i++;
};
return array
};
google.script.run.withSuccessHandler(onSuccess).withUserObject(cities).populate();
//Create the dropdown menu for the cities
for (city in cities) {
var element = $("#city1").append("<option value=" + cities[city].toLowerCase() + ">" + cities[city] + "</option>");
console.log(city);
};
[...]
});
HTML:
<select id="city1" name="city" placeholder="City"><option id="citydummy">City</option></select>
Google Apps Script:
function populate() {
var db = SpreadsheetApp.openById('SHEETID');
var check = true;
var array = [];
for (var i = 2; i < db.getLastRow(); i++) {
db.getActiveSheet().getRange(i, "1").getValue()
array.push(db.getActiveSheet().getRange(i, "1").getValue())
}
return array;
}
Many thanks in advance for anyone who will contribute!
How about the following modification for JS? HTML and GAS are not modified. Data obtained at populate() is directly sent to onSuccess(), and imported the data to the list.
JS :
$(function() {
google.script.run.withSuccessHandler(onSuccess).populate();
});
function onSuccess(cities) {
for (city in cities) {
var element = $("#city1").append("<option value=" + cities[city].toLowerCase() + ">" + cities[city] + "</option>");
console.log(city);
};
};
If I misunderstand your situation, I'm sorry.

Fill select option dropdown list from array in iframe using javascript

I am trying to fill in a select dropdown list with an array of options from a call to our server. I have the server call setup to run and fill a hidden iframe and that part works fine. I need to get the data from the iframe and use that array to fill the option list.
In the main/parent page I have this table cell for the select list:
<tr>
<td><select id="ymm_model" name="vmodel">
<option value="" selected="selected">Select Model</option>
</select></td>
</tr>
This function is in the main/parent in the scripts area and is called by a prior select list onchange, and was my attempt to fill the select list after running the call to fill the iframe. The filling of the iframe works and shows the data.
function getModels(make) // open iframe and do call
{
window.frames['dataframe'].window.location.href='http://www.atkcores.com/cgi-bin /vinholmodel.cgi?myear='+document.vinhol.ymm_year.value+'&mmake='+make;
var select = document.getElementById("ymm_model");
var mods = document.getElementById('dataframe').contentWindow.document.getElementById['models'];
for (var i = 0; i < mods.length; i++) {
var option = document.createElement('option');
option.text = option.value = mods[i];
select.add(option, 1)
}
}
I also tried this function which would run from the page that loads into the iframe from my server script and after the page loaded.
function takedata(passed)
{
var select = document.getElementById("ymm_model");
var mods = document.getElementById('dataframe').contentWindow.document.getElementById['models'];
for (var i = 0; i < mods.length; i++) {
var option = document.createElement('option');
option.text = option.value = mods[i];
select.add(option, 1)
}
}
This is the page that is formed in my server process that fills the iframe.
<html>
<head>
<meta content="text/html; charset=ISO-8859-1"
http-equiv="content-type">
</head>
<script>
function init()
{
window.parent.takedata(document.getElementById("moddata").value);
return true;
}
</script>
<body onload="init();">
<form name="vinmodels">
<div id="moddata"> var models =["ACCORD","CIVIC","CR-V","DEL SOL","ODYSSEY","PASSPORT","PRELUDE"]; </div>
</form>
</body>
</html>
The content in the moddata div is what I need to use to fill the select list.
Thanks for any guidance or suggestions you have,
Scott
I think you're making it more complicated than it needs to be. You need to get an array of data from a server, which is what AJAX was all but built for.
Your server should instead of sending an HTML response, send an application/json response with the array. It should look like this:
{
"models": ["ACCORD","CIVIC","CR-V","CR-Z","CROSSTOUR","FIT","INSIGHT","ODYSSEY","PILOT","RIDGELINE"]
}
Remember that a JSON object relies on key-value pairs. We only have one piece of data (the models array), so we've assigned it the key "models".
From here, just pull in the data using your favorite AJAX methodology. I'm using jQuery for this example, but you can also use XHR requests for a non-jQuery approach. I've included a fiddle, but note that the fiddle won't "work" properly since it is not on the atkcores.com domain (this is a Cross-Origin Sharing issue).
You should however be able to understand the gist of it and create your own version.
//This is what your server should respond with a type of 'application/json'
var serverResponse = '{ "models": ["ACCORD","CIVIC","CR-V","CR-Z","CROSSTOUR","FIT","INSIGHT","ODYSSEY","PILOT","RIDGELINE"] }';
//This uses jQuery for a quick demonstration, look up how to do AJAX without jQuery using XHR objects if you don't want to use jQuery
$(document).ready(function() {
$.get('http://www.atkcores.com/cgi-bin/vinholmodel.cgi?myear=2014&mmake=honda')
.success(function(data) {
//This will not work on the demo since your server doesn't support CORS, but
//this is where you would process the data.
handleResponse(data);
}).fail(function(jqXHR, message) {
//In this demonstration, this will always hit because of the above CORS issue
});
//Pretend the above AJAX worked, we handle the response
//Since your server is responding with 'application/json', we don't need to parse
//the string above as we do here
handleResponse(JSON.parse(serverResponse));
});
function handleResponse(data) {
//Server passes the array in a JSON object with the key 'models'
var modelsArray = data.models;
var select = document.getElementById('ymm_model');
for (var i = 0; i < modelsArray.length; i++) {
var option = document.createElement('option');
option.text = option.value = modelsArray[i];
select.add(option, 1);
}
}
http://jsfiddle.net/vg0g7gzL/

Retrieve the disabled attributes even after page refresh using localStorage

I have an HTML code with a select tag where the options are dynamically populated. Once the onchange event occurs the option selected gets disabled. And also if any page navigation happens the options populated previously are retrieved.
In my case once options are populated and any option is selected gets disabled( intention to not allow the user to select it again). So there might be a case where out of 3 options only two are selected and disabled so once I refresh and the options not selected previously should be enabled. And the options selected previously should be disabled. But my code enables all the options after refresh. How can I fix this?
html code
<select id="convoy_list" id="list" onchange="fnSelected(this)">
<option>Values</option>
</select>
js code
//This function says what happnes on option change
function fnSelected(selctdOption){
var vehId=selctdOption.options[selctdOption.selectedIndex].disabled=true;
localStorage.setItem("vehId",vehId);
//some code and further process
}
//this function says the process on the drop-down list --on how data is populated
function test(){
$.ajax({
//some requests and data sent
//get the response back
success:function(responsedata){
for(i=0;i<responsedata.data;i++):
{
var unitID=//some value from the ajax response
if(somecondition)
{
var select=$(#convoy_list);
$('<option>').text(unitID).appendTo(select);
var conArr=[];
conArr=unitID;
test=JSON.stringify(conArr);
localStorage.setItem("test"+i,test);
}
}
}
});
}
//In the display function--on refresh how the stored are retrievd.
function display(){
for(var i=0;i<localStorage.length;i++){
var listId=$.parseJSON(localStorage.getItem("test"+i)));
var select=$(#list);
$('<option>').text(listId).appendTo(select);
}
}
In the display function the previously populated values for the drop down are retrieved but the options which were selected are not disabled. Instead all the options are enabled.
I tried the following in display function
if(localStorage.getItem("vehId")==true){
var select=$(#list);
$('<option>').text(listId).attr("disabled",true).appendTo(select);
}
But this does not work.
Elements on your page shouldn't have same ids
<select id="convoy_list" onchange="fnSelected(this)">
<option>Values</option>
</select>
In your fnSelected() function you always store item {"vehId" : true} no matter what item is selected. Instead, you should for example first assign some Id to each <option\> and then save the state only for them.
For example:
function test(){
$.ajax({
//some requests and data sent
//get the response back
success:function(responsedata){
for(i=0;i<responsedata.data;i++):
{
var unitID=//some value from the ajax response
if(somecondition)
{
var select=$("#convoy_list"); \\don't forget quotes with selectors.
var itemId = "test" + i;
$('<option>').text(unitID).attr("id", itemId) \\we have set id for option
.appendTo(select);
var conArr=[];
conArr=unitID;
test=JSON.stringify(conArr);
localStorage.setItem(itemId,test);
}
}
}
});
}
Now we can use that id in fnSelected():
function fnSelected(options) {
var selected = $(options).children(":selected");
selected.prop("disabled","disabled");
localStorage.setItem(selected.attr("id") + "disabled", true);
}
And now in display():
function display(){
for(var i=0;i<localStorage.length;i++){
var listId = $.parseJSON(localStorage.getItem("test"+i)));
var select = $("convoy_list");
var option = $('<option>').text(listId).id(listId);
.appendTo(select);
if(localStorage.getItem(listId + "disabled") == "true"){
option.prop("disabled","disabled");
}
option.appendTo(select);
}
}
Also maybe not intended you used following shortcut in your fnSelected:
var a = b = val;
which is the same as b = val; var a = b;
So your fnSelected() function was equivalent to
function fnSelected(selctdOption){
selctdOption.options[selctdOption.selectedIndex].disabled=true;
var vehId = selctdOption.options[selctdOption.selectedIndex].disabled;
localStorage.setItem("vehId",vehId); \\ and "vehId" is just a string, always the same.
}
Beware of some errors, I didn't test all of this, but hope logic is understood.

Categories

Resources