dynamic dropdown for file selection - javascript

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.

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.

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/

how to fetch data from dynamically added textboxes from jsp code

Urgent..Anyone please Assist
how to access data from the elements added via javascript dynamically using the jsp code.
i am adding empty records on .jsp page using javascript (by calling a below function on click event of button) as :-
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
element1.value="";
cell1.appendChild(element1); //and so on for 5 columns too
Main problem is that i am not able to access these dynamically added textboxes values from my jsp code. (because they have been created dynamically by javascript)
Now,i want to save the value from these dynamically added textboxes(in form of table) from the .jsp page to database using jsp...(there can be several rows generated depending upon user input)
or else suggest me code to create them dynamically so that i can fetch data from added dynamic textboxes on jsp page.
And please ..i don't want to go for servlet concept...wants using jsp only..
thnks ....
Why dont you provide unique id and name to the textboxes you are adding?
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
element1.value="";
element1.id="empName[0]";
element1.name="empName[0]";
cell1.appendChild(element1);
Like
<input type="text" id="empName[0]" name="empName[0]" value=""/>
<input type="text" id="empName[1]" name="empName[1]" value=""/>
Then on server side you can,
request.getParameter("empName[0]");
request.getParameter("empName[1]");
Try this:
var textboxes = [];
var inputs = cell1.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++){
if(inputs[i].type == "text")
textboxes.push(inputs[i]);
// or get name value pairs if not disabled:
// if(!inputs[i].disabled)
// myNameValues.push({ name: inputs[i].name, value: inputs[i].value });
}

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

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>

Removing child nodes on dynamic select

I'm creating a dynamic selection form. Basically the user picks an option from the select and then depending on what option they chose it goes into a data object and then generates a new selection based on their previous answer. After they answer 3 questions regarding their vehicle choice it prints out their vehicle choice.
The problem I'm running into is having the ability to change a previous option on the fly. I'd like to have them be able to change a previous selection and it would remove the later selection
Ex. The user first selects Car, Ford and a selection for model is displayed. If the user went back and changed Car to Truck. I would like to remove Ford and the model selection. Here is the part of the code I have that holds the data and creates the new selections dynamically
var data=new Object();// create a new data object to hold info
data['init']=['Car','Truck','SUV'];
data['Car']=['Audi','Dodge','Ford','Volkswagon'];
data['Audi']=['A4','TT','R8'];
data['Dodge']=['Charger','Challenger','Stealth'];
data['Ford']=['Focus','Fusion','Mustang'];
data['Volkswagon']=['Jetta','GTI','Beetle'];
data['Truck']=['Dodge Truck','Ford Truck','Toyota Truck'];
data['Dodge Truck'] = ['Ram-1500','Ram-2500','Ram-3500'];
data['Ford Truck'] = ['F-150','F-250','Ranger'];
data['Toyota Truck'] = ['Tundra','Tacoma'];
data['SUV']=['Dodge SUV','Ford SUV','Toyota SUV'];
data['Dodge SUV'] = ['Durango','Journey','Caliber'];
data['Ford SUV'] = ['Escape','Edge','Explorer'];
data['Toyota SUV'] = ['Rav4','Highlander','4runner'];
var hold = data['init'];//Sets data to 'init' by default
var selectedArray = [];//This array holds the selected options (to be used to display the vehicle name)
function init(){//call first to create the first select box and populate with 'init'
firstSelect = document.createElement('select');
firstSelect.setAttribute("onChange","createSelect(this.value)");
createSelect('init');
}
//Main create function for select boxes
function createSelect(value){
selectHold = value;//sets selectHold to the value of the selected item (this will be used for displaying the name in disName)
//This just prevents it from adding "Car, Truck or SUV to the selectedArray
if(value != 'init' && value != 'Truck' && value != 'Car' && value != 'SUV' && value != 'Select your vehicle options'){
selectedArray.push(selectHold);
}
hold=data[value];// sets this holder to the value of the selected item for the if statement
if(hold){ //just checks to see if hold exists
var selEle = document.createElement('select');//creates new select element
//gives selEle onchange function
selEle.setAttribute("onChange","createSelect(this.value)");
//Creates the "default" option. Forcing them to pick something.
var defaultOpt = document.createElement('option');
var vehInfo = document.createTextNode("Select your vehicle options");
defaultOpt.appendChild(vehInfo);
selEle.appendChild(defaultOpt);
//Populates the options and adds it to the document
for(var i = 0, l = hold.length; i < l; i++){
var newOpt = document.createElement('option');
newOpt.appendChild(document.createTextNode( hold[i]));
newOpt.setAttribute('value',hold[i]);
selEle.appendChild(newOpt);
}
//put select on the page
document.getElementById('top-container').appendChild(selEle);
}
else{ //if not, then put out final form
disName(selectHold,selectedArray);//call disName function an dpass it the value of selectHold
}
}
HTML:
<div id="top-container">
<h1>Awesome<br/>
Car<br/>
Picker</h1>
</div>
<div id="middle-container">
<h2>Your vechle choice:</h2>
</div>
<div id="bottom-container">
<div id="mail-form">
<form name='mail-form'>
<label>Name</label>
<input name="name" autofocus>
<label>Email</label>
<input name="email">
<label>Credit Card number</label>
<input name="cc">
<input id="submit" name="submit" value="Submit" onClick="validate()">
</form>
</div>
</div>
<body>
What I'm thinking is to check the to see if the selection is the lastChild of the parent node (top container). and if it is not then delete the child of that until it's at the point where it's only the selection that was changed and any selection that fell before it.
Any suggestions?
Thanks!
In your createSelect function, assign an ID to the new element using something like selEle.id = 'newID';.
Before calling the createSelect function, check to see if the new element exists and if so, remove it:
if (document.getElementById('newID'))
document.getElementById('top-container').removeChild(document.getElementById('newID'));

Categories

Resources