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

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.

Related

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.

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 populate a dropdown list based on values of the another list?

I want to implement a search box same as this, at first, just first dropdown list is active once user selects an option from the first dropbox, the second dropdown box will be activated and its list will be populated.
<s:select id="country" name="country" label="Country" list="%{country} onchange="findCities(this.value)"/>
<s:select id="city" name="city" label="Location" list=""/>
Jquery chained plugin will serve your purpose,
https://plugins.jquery.com/chained/
usage link - http://www.appelsiini.net/projects/chained
this plugin will chain your textboxes.
Try this code where based on your needs you have to populate it with your options:
var x;
$('#pu-country').on('change', function () {
if (this.value != '0') {
$('#pu-city').prop('disabled', false);
$('#pu-city').find("option").not(":first").remove();
$('#pu-location').prop('disabled', true);
$('#pu-location').val("Choose");
switch (this.value) {
case 'A':
x = '<option value="A.1">A.1</option><option value="A.2">A.2</option><option value="A.3">A.3</option>'
}
$('#pu-city').append(x)
} else {
$('#pu-location').prop('disabled', true);
$('#pu-location').val("Choose");
$('#pu-city').prop('disabled', true);
$('#pu-city').val("Choose");
}
});
$('#pu-city').on('change', function () {
if (this.value != '0') {
$('#pu-location').prop('disabled', false);
$('#pu-location').find("option").not(":first").remove();
switch (this.value) {
case 'A.1':
x = '<option value="A.1.1">A.1.1</option><option value="A.1.2">A.1.2</option><option value="A.1.3">A.1.3</option>'
break;
case 'A.2':
x = '<option value="A.2.1">A.2.1</option><option value="A.2.2">A.2.2</option><option value="A.2.3">A.2.3</option>'
break;
case 'A.3':
x = '<option value="A.3.1">A.3.1</option><option value="A.3.2">A.3.2</option><option value="A.3.3">A.3.3</option>'
break;
}
$('#pu-location').append(x)
} else {
$('#pu-location').prop('disabled', true);
$('#pu-location').val("Choose");
}
});
I have also set up and a demo to see the functionallity with more options.
FIDDLE
Your code should be something like this:
$(country).change(function(){
var l=Document.getElementByID("country");
for(i=0;i<=l.length;i++)
{
if(l.options[i].selected?)
{
text_array=[HERE YOU NEED TO ADD THE CITIES OF l.options[i].text];
val_array=[HERE YOU NEED TO ADD THE VALUES OF THECITIES OF l.options[i].text];
}
}
var c=Document.getElementByID("city");
c.options.text=[];
c.options.value=[];
//You now should have an empty select.
c.options.text=text_array ;
c.options.value=val_array ;
});
As I don't know, what kind of DB you use, to have the cities connected to their countrys, I can't tell you, what to put into the uppercase text...
Ciao j888, in this fiddle i tried to reconstruct the same system as the site you provided the link
the number of states cityes and locality is less but the concept remains the same
If you want to add a new state you must enter a new html options in select#paese with an id.
Then you have add in obj.citta a property with this id name and an array of cityes for a value.
The same thing for obj.localita where you will create an array of arrays.
The jQuery code you need is
<script type="text/javascript">
$(document).ready(function(){
var obj={
citta:{ //value is the same of option id
albania:['Durres','Tirana'],
austria:['Vienna','innsbruck','Graz'],
},
localita:{//for every city create a sub array of places
albania:[['località Durres1','località Durres 2'],['località Tirana','località Tirana 2']],
austria:[['località Vienna','località Vienna 2'],['località innsbruck','località innsbruck 2'],['località Graz','località Graz 2','località Graz 3']],
}
}
$('#paese').on('change',function(){
$('#località').attr('disabled','disabled').find('option').remove()
var quale=$(this).find('option:selected').attr('id')
var arr=obj.citta[quale]
if(arr){
$('#citta').removeAttr('disabled')
$('#citta option.added').remove()
for(i=0;i<arr.length;i++){
$('<option class="added">'+arr[i]+'</option>').appendTo('#citta')
}
}
})
$('#citta').on('change',function(){
var ind=($(this).find('option:selected').index())-1
var quale=$('#paese').find('option:selected').attr('id')
var arr=obj.localita[quale][ind]
if(arr){
$('#località').removeAttr('disabled')
$('#località option.added').remove()
for(i=0;i<arr.length;i++){
$('<option class="added">'+arr[i]+'</option>').appendTo('#località')
}
}
})
})
</script>
If this solution does not suit your needs, i apologize for making you lose time.
Hi i have done this for license and its dependent subject in yii 1.
The license dropdown
//php code
foreach($subject as $v) {
$subj .= $v['licenseId'] . ":" . $v['subjectId'] . ":" . $v['displayName'] . ";";
}
Yii::app()->clientScript->registerScript('variables', 'var subj = "' . $subj . '";', CClientScript::POS_HEAD);
?>
//javascript code
jQuery(document).ready(function($) {
//subject. dependent dropdown list based on licnse
var ty, subjs = subj.split(';'), subjSel = []; //subj register this varible from php it is
for(var i=0; i<subjs.length -1; i++) { //-1 caters for the last ";"
ty = subjs[i].split(":");
subjSel[i] = {licId:ty[0], subjId:ty[1], subjName:ty[2]};
}
//dropdown license
jQuery('#license#').change(function() {
$('#add').html(''); //clear the radios if any
val = $('input[name="license"]:checked').val();
var selectVals = "";
selectVals += '<select>';
for(var i=0; i<subjSel.length; i++) {
if(subjSel[i].licId == val) {
if(subjSel[i].subjId *1 == 9) continue;
selectVals += '<option value="'+subjSel[i].subjId+'">'+subjSel[i].subjName+'</option>';
}
}
selectVals += '</select>';
$("#subject").html(selectVals);
});
});
You seem to be asking two questions:
QUESTION 1. How to have a disabled select box (the second and third select boxes in the case of your example) which is activated upon the selection of an option from the first select box.
ANSWER 1:
simply use the disabled=true/false as below...
<select id="country" name="country" label="Country" onchange="document.getElementById('city').disabled=false; findCities(this.value)"/>
<select id="city" name="city" label="Location" disabled=true/>
NOTE: I changed "s:select" to "select" on the basis that your question does not make reference or tag the Struts framework that uses this syntax.
QUESTION 2: How to populate the second select box when a selection is made in the first.
ANSWER 2: There are many ways to do this, and the choice depends on where you have the data to populate the lists with. In the case of your Rentalcars example, if you chose Barbados, the browser sends an ajax GET request to "http://www.rentalcars.com/AjaxDroplists.do;jsessionid=5DCBF81333A88F37BC7AE15D21E10C41.node012a?country=Barbados&wrapNonAirports=true" -try clicking on this link and you will see what that request is sending back. This '.do' address is a server side file of a type used with the Struts framework I mentioned above.
A more conventional approach, which would be included in your function findCities(country)would be to send an AJAX request to a PHP script which queries a database and sends back an array of place names to the browser. The AJAX javascript code includes instructions as to what to do with the response. Without knowing more about where you want to store your list, giving an example of this would most likely not be useful.
Alternatively, the whole list of places could be included in the javascript script as an array (as demonstarated by Devima, above), in a text document on the server as comma separated values, or you could save it to a browser database like WebSQL or IndexedDB if offline use would be useful.
When you have got your list, probably as an array of values, you could save the array as a variable eg. var cities=result (in the case of a simple ajax request). You will then need to iterate through cities, for example
for (var i = 0; i < cities.length; i++){
var place=cities[i];//an individual city name
document.getElementById("city").innerHTML+="<option value='" + place + "'>" + place + "</option>";//adds an 'option' with the value being the city name and the text you see being the city name
}
IMO this is the base case AngularJS was designed to completely alleviate. Check it out!

How to get value of data-flag

Community, I have a select drop down which is trying to pass two variables to javascript. The first variable is (source_id) and the second is (source_flag).
My select looks like the following...
<select id="ticket_source" name="ticket_source" onchange="showEmail(this)">
<option value="">Select Source</option>
I use query to populate remaining options.
$get_sources = mysql_query("select source_id, source_name, source_flag from ticket_source order by source_name ASC");
while(($source_list = mysql_fetch_assoc($get_sources)))
{
echo '<option value="'.$source_list['source_id'].'" data-flag="'.$source_list['source_flag'].'">'.$source_list['source_name'].'</option>
}
<option value="0">Other</option>
</select>';
My javascript will make a hidden div appear. I'm trying to obtain the value stored in the data-flag attribute, and I'm not quite sure if there is a certain route to do that.
function showEmail(element)
{
var id = element.value;
var divTwo = document.getElementById("ticket_source");
var flag = divTwo.getAttribute('data-flag');
alert(flag);
// Do something with flag...
var div = document.getElementById("received");
if(id == 2 || id == 3 || id == 5)
{
div.style.display = 'block';
}
else
{
div.style.display = 'none';
}
}
How about this in pure javascript
var flag =document.getElementById('ticket_source').options[select.selectedIndex].data-flag;
or
var flag =element.options[element.selectedIndex].data-flag;
var flag =element.options[element.selectedIndex].getAttribute('data-flag');
See Fiddle Here
Try this:
var flag = document.querySelector('#ticket_source').dataset.flag; // using javascript
var flag = $('#ticket_source').data('flag'); // using jquery
JSBIN Link: http://jsbin.com/ujiday/228/
In modern browsers you could do this
document.getElementById('myThing').dataset.flag
However, that won't work in non-HTML5 compliant browsers, so you'd want to use getAttribute like you've done in your code above.
Alternatively if you're using jQuery, Mohit Pandey's answer would be good.
Edit: Looking at your code, it also looks like you're trying to pull the data value from the select box, while in your PHP you're adding it to the options, which would explain why it was returning null/undefined.
Made a fiddle (using jQuery)
http://jsfiddle.net/QAsgN/

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>

Categories

Resources