I am trying to loop 100 values from an API into a dropdown list. When the function runs the page loads all 100 values but inserts them into the list on 1 line, rather than on 100 separate lines. I have tried adding a break tag to the loop but that didn't work.
How do you separate each item onto its own line?
// GET STATION NAMES AND PUT THEM INTO DROPDOWN LIST
function addressList() {
// var xhr = new XMLHttpRequest();
// xhr.open('GET', 'https://api.jcdecaux.com/vls/v1/stations?contract=Dublin&apiKey=xxxxxxxxxx');
// xhr.onreadystatechange = function() {
// if (xhr.readyState == 4 && xhr.status == 200) {
// var items = JSON.parse(xhr.responseText);
var items = [{"address":"Smithfield North"},{"address":"Parnell Square North"},{"address":"Pearse Street"},{"address":"Excise Walk"},{"address":"Fitzwilliam Square West"},{"address":"St. James Hospital (Central)"},{"address":"Hanover Quay"},{"address":"Oliver Bond Street"},{"address":"Collins Barracks Museum"},{"address":"Brookfield Road"},{"address":"Clonmel Street"},{"address":"Mount Street Lower"},{"address":"Christchurch Place"},{"address":"Grantham Street"},{"address":"York Street East"},{"address":"Portobello Road"},{"address":"Parnell Street"},{"address":"Frederick Street South"},{"address":"Fownes Street Upper"},{"address":"Clarendon Row"},{"address":"Custom House"},{"address":"Benson Street"},{"address":"Fenian Street"},{"address":"South Dock Road"},{"address":"The Point"},{"address":"Lime Street"},{"address":"Kilmainham Gaol"},{"address":"Guild Street"},{"address":"Herbert Place"},{"address":"Western Way"},{"address":"Newman House"},{"address":"King Street North"},{"address":"Herbert Street"},{"address":"Earlsfort Terrace"},{"address":"Golden Lane"},{"address":"Deverell Place"},{"address":"John Street West"},{"address":"City Quay"},{"address":"Exchequer Street"},{"address":"Hatch Street"},{"address":"Charlemont Street"},{"address":"Hardwicke Place"},{"address":"Wolfe Tone Street"},{"address":"Francis Street"},{"address":"Greek Street"},{"address":"High Street"},{"address":"North Circular Road"},{"address":"Talbot Street"},{"address":"Sir Patrick's Dun"},{"address":"New Central Bank"},{"address":"Georges Quay"},{"address":"Mount Brown"},{"address":"Royal Hospital"},{"address":"Heuston Station (Central)"},{"address":"Townsend Street"},{"address":"Portobello Harbour"},{"address":"Custom House Quay"},{"address":"Molesworth Street"},{"address":"Kilmainham Lane"},{"address":"Market Street South"},{"address":"Kevin Street"},{"address":"Eccles Street East"},{"address":"Grand Canal Dock"},{"address":"Merrion Square East"},{"address":"York Street West"},{"address":"St. Stephen's Green South"},{"address":"Denmark Street Great"},{"address":"Heuston Station (Car Park)"},{"address":"St. Stephen's Green East"},{"address":"Eccles Street"},{"address":"Mater Hospital"},{"address":"Blessington Street"},{"address":"Merrion Square West"},{"address":"Convention Centre"},{"address":"Hardwicke Street"},{"address":"Smithfield"},{"address":"Dame Street"},{"address":"Sandwith Street"},{"address":"Princes Street / O'Connell Street"},{"address":"Grattan Street"},{"address":"St James Hospital (Luas)"},{"address":"Bolton Street"},{"address":"Strand Street Great"},{"address":"Barrow Street"},{"address":"Mountjoy Square West"},{"address":"Wilton Terrace"},{"address":"Leinster Street South"},{"address":"James Street"},{"address":"Parkgate Street"},{"address":"Heuston Bridge (South)"},{"address":"Cathal Brugha Street"},{"address":"Rothe Abbey"},{"address":"Upper Sherrard Street"},{"address":"Fitzwilliam Square East"},{"address":"Harcourt Terrace"},{"address":"Jervis Street"},{"address":"Ormond Quay Upper"},{"address":"Emmet Road"},{"address":"Heuston Bridge (North)"},{"address":"Blackhall Place"}];
var output = '<select>'
for (var i in items) {
output += '<option>' + items[i].address + '</option> <br>'
}
output += '</select>'
document.getElementById("replaceOption").innerHTML = output
// }
// }
// xhr.send();
};
<!DOCTYPE html>
<html>
<head>
<script src="stations.js"></script>
<title></title>
</head>
<body onload="addressList()">
<div>
<div id="addressDropdown">
<form>
<select>
<option id="addressList" value="select station" selected="selected">Select Station..</option>
<option id="replaceOption">0</option>
</select>
<br>
<input type="submit" value="Go" id="sumbit" href="#">
</form>
</div>
</div>
</body>
</html>
Append your options to the select element it's self. The reason why it's all on one line is because you're adding the new options inside an existing option rather than appending them after the existing option.
// GET STATION NAMES AND PUT THEM INTO DROPDOWN LIST
function addressList() {
var items = [{"address":"Smithfield North"},{"address":"Parnell Square North"},{"address":"Pearse Street"},{"address":"Excise Walk"},{"address":"Fitzwilliam Square West"},{"address":"St. James Hospital (Central)"},{"address":"Hanover Quay"},{"address":"Oliver Bond Street"},{"address":"Collins Barracks Museum"},{"address":"Brookfield Road"},{"address":"Clonmel Street"},{"address":"Mount Street Lower"},{"address":"Christchurch Place"},{"address":"Grantham Street"},{"address":"York Street East"},{"address":"Portobello Road"},{"address":"Parnell Street"},{"address":"Frederick Street South"},{"address":"Fownes Street Upper"},{"address":"Clarendon Row"},{"address":"Custom House"},{"address":"Benson Street"},{"address":"Fenian Street"},{"address":"South Dock Road"},{"address":"The Point"},{"address":"Lime Street"},{"address":"Kilmainham Gaol"},{"address":"Guild Street"},{"address":"Herbert Place"},{"address":"Western Way"},{"address":"Newman House"},{"address":"King Street North"},{"address":"Herbert Street"},{"address":"Earlsfort Terrace"},{"address":"Golden Lane"},{"address":"Deverell Place"},{"address":"John Street West"},{"address":"City Quay"},{"address":"Exchequer Street"},{"address":"Hatch Street"},{"address":"Charlemont Street"},{"address":"Hardwicke Place"},{"address":"Wolfe Tone Street"},{"address":"Francis Street"},{"address":"Greek Street"},{"address":"High Street"},{"address":"North Circular Road"},{"address":"Talbot Street"},{"address":"Sir Patrick's Dun"},{"address":"New Central Bank"},{"address":"Georges Quay"},{"address":"Mount Brown"},{"address":"Royal Hospital"},{"address":"Heuston Station (Central)"},{"address":"Townsend Street"},{"address":"Portobello Harbour"},{"address":"Custom House Quay"},{"address":"Molesworth Street"},{"address":"Kilmainham Lane"},{"address":"Market Street South"},{"address":"Kevin Street"},{"address":"Eccles Street East"},{"address":"Grand Canal Dock"},{"address":"Merrion Square East"},{"address":"York Street West"},{"address":"St. Stephen's Green South"},{"address":"Denmark Street Great"},{"address":"Heuston Station (Car Park)"},{"address":"St. Stephen's Green East"},{"address":"Eccles Street"},{"address":"Mater Hospital"},{"address":"Blessington Street"},{"address":"Merrion Square West"},{"address":"Convention Centre"},{"address":"Hardwicke Street"},{"address":"Smithfield"},{"address":"Dame Street"},{"address":"Sandwith Street"},{"address":"Princes Street / O'Connell Street"},{"address":"Grattan Street"},{"address":"St James Hospital (Luas)"},{"address":"Bolton Street"},{"address":"Strand Street Great"},{"address":"Barrow Street"},{"address":"Mountjoy Square West"},{"address":"Wilton Terrace"},{"address":"Leinster Street South"},{"address":"James Street"},{"address":"Parkgate Street"},{"address":"Heuston Bridge (South)"},{"address":"Cathal Brugha Street"},{"address":"Rothe Abbey"},{"address":"Upper Sherrard Street"},{"address":"Fitzwilliam Square East"},{"address":"Harcourt Terrace"},{"address":"Jervis Street"},{"address":"Ormond Quay Upper"},{"address":"Emmet Road"},{"address":"Heuston Bridge (North)"},{"address":"Blackhall Place"}];
for (var i in items) {
document.getElementById("mySelect").innerHTML += '<option>' + items[i].address + '</option>';
}
};
<!DOCTYPE html>
<html>
<head>
<script src="stations.js"></script>
<title></title>
</head>
<body onload="addressList()">
<div>
<div id="addressDropdown">
<form>
<select id="mySelect">
<option id="addressList" value="select station" selected="selected">Select Station..</option>
<option id="replaceOption">0</option>
</select>
<br>
<input type="submit" value="Go" id="sumbit" href="#">
</form>
</div>
</div>
</body>
</html>
document.addEventListener('DOMContentLoaded', function () {
let selectEl = document.getElementById('select-el');
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (res) {
if (xhr.readyState == 4 && xhr.status == 200) {
let items = JSON.parse(xhr.responseText);
console.log(items);
items.forEach(function (item) {
let option = document.createElement('option');
option.value = item.name;
option.innerText = item.address;
selectEl.appendChild(option);
});
}
}
xhr.open('GET', 'https://api.jcdecaux.com/vls/v1/stations?contract=Dublin&apiKey=xxxxxxxxxx');
xhr.send();
});
<!DOCTYPE html>
<html>
<head>
<script src="stations.js"></script>
<title></title>
</head>
<body>
<div>
<div id="addressDropdown">
<form>
<select id="select-el"></select>
<br/>
<input type="submit" value="Go" id="sumbit" href="#" />
</form>
</div>
</div>
</body>
</html>
The problem is that you're inserting an extra <select> into the existing select. Here's what your output HTML looks like:
<form>
<select>
<option id="addressList" ...</option>
<option id="replaceOption">
<select>
<option>Smithfield North</option>
...
What you want to do instead is to append the options to the select box directly, rather than replacing the existing one. Note that the select box has an ID now instead of the option box. Here's the code that you need:
//GET STATION NAMES AND PUT THEM INTO DROPDOWN LIST
function addressList() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.jcdecaux.com/vls/v1/stations?contract=Dublin&apiKey=xxxxxxxxxx');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var items = JSON.parse(xhr.responseText);
// get the select box by id
var addressList = document.getElementById("addressList")
// loop through all of the items and add an option to the list
for (var i in items) {
var option = document.createElement("option");
option.text = items[i].address;
option.value = i
addressList.add(option)
}
}
}
xhr.send();
};
<!DOCTYPE html>
<html>
<head>
<script src="stations.js"></script>
<title></title>
</head>
<body onload="addressList()">
<div>
<div id="addressDropdown">
<form>
<select id="addressList">
<option value="select station" selected="selected">Select Station..</option>
</select>
<br>
<input type="submit" value="Go" id="sumbit" href="#">
</form>
</div>
</div>
</body>
</html>
Related
Here, I have a nice autocomplete dropdown that, given a city typed by the user, the page will show all possible city-state-country triplets. For example the name Guadalajara would suggest
Guadalajara de Buga, Valle del Cauca Department, Colombia
Guadalajara, Castilla La Mancha, Spain
and
Guadalajara, Jalisco, Mexico
The code works perfectly from both the backend and the frontend, the only problem left is that the autosuggest drop down menu will only work with the mouse and not with the keyboard. The Up and Down arrow keys will not allow to navigate through the most appropriate choice and pressing esc doesn't cancel the menu.
I tried everything and I have no idea about what is missing to make this work with the keyboard as well. I would like to find a solution with pure vanilla JavaScript and that would involve the least possible changes in the rest of working code. Here the entire code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Vanilla Javascript Cities Test</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma#0.8.2/css/bulma.min.css">
</head>
<body id="body">
<div class="title has-text-centered" id="main"></div>
<section id="form" class="section" onclick="clearCities()">
<div class="container">
<h1 class="title">Vanilla Cities Javascript</h1>
<!-- Row for City, State and Country -->
<div id="location">
<div class="field">
<div class="control">
<div id="cities-dropdown" class="dropdown">
<div class="dropdown-trigger">
<input name="cities" id="cities" onkeyup="getCities()" maxlength="50" class="input" type="text" placeholder="Enter a city" aria-haspopup="true" aria-controls="dropdown-menu3" -autocomplete="off" required
>
</div>
<div class="dropdown-menu" id="dropdown-menu3" role="menu">
<div id="cities-dropdown-content" class="dropdown-content">
<!-- content -->
<a class="dropdown-item"></a>
</div>
</div>
</div> Clear
</div>
<span class="is-size-7 has-text-info">(If your location doesn't appear immediately, try to type slower).</span>
</div>
<!-- City Field -->
<div class="field">
<div class="control">
<input name="city" id="city" class="input" type="text" placeholder="City" required>
</div>
</div>
<!-- State Field -->
<div class="field">
<div class="control">
<input name="state" id="state" class="input" type="text" placeholder="State" required>
</div>
</div>
<!-- Country Field -->
<div class="field">
<div class="control">
<input name="country" id="country" class="input" type="text" placeholder="Country" required>
</div>
</div>
</div>
</div>
</section>
</body>
<script>
function getCities(){
var inputCity = document.getElementById('cities').value;
const city = changeCase(inputCity);
if(city.length <= 2){
return false;
}
// Create request to get cities locations
var request = new XMLHttpRequest();
request.addEventListener("load", transferComplete);
request.open("GET", "/cities/?cityname=" + city);
request.send();
// Called when transfer is complete
function transferComplete(event){
//alert(event.srcElement.response);
locations = JSON.parse(event.srcElement.response);
// Return false if no matching city was found
if(locations.length == 0){
return false;
}
// Append choices
dropContent = document.getElementById('cities-dropdown-content');
dropContent.innerHTML = "";
for (var i = 0; i < locations.length; i++) {
var link = document.createElement("a");
link.setAttribute("onclick", "setCity(" + JSON.stringify(locations[i].name) + "," + JSON.stringify(locations[i].state) + "," + JSON.stringify(locations[i].country) + ")");
link.setAttribute("class", "dropdown-item");
link.innerHTML = locations[i].name + ", " + locations[i].state.name + ", " + locations[i].country.name
dropContent.append(link);
}
document.getElementById("cities-dropdown").classList.add("is-active");
}
// document.getElementById("products-list").innerHTML = html;
}
function setCity(city, state, country){
document.getElementById('cities').value = city+', '+state.name+', '+country.name;
document.getElementById('city').value = city;
document.getElementById('state').value = state.name;
document.getElementById('country').value = country.name;
document.getElementById('cities-dropdown-content').innerHTML = "";
document.getElementById("cities-dropdown").classList.remove("is-active");
}
function clearCities(){
document.getElementById('cities-dropdown-content').innerHTML = "";
document.getElementById("cities-dropdown").classList.remove("is-active");
}
function deleteEntry(e){
e.preventDefault();
document.getElementById('cities').value = '';
}
function changeCase(inputCity){
return inputCity
.replace(/([a-z])([A-Z])/g, function (allMatches, firstMatch, secondMatch) {
return firstMatch + " " + secondMatch;
})
.toLowerCase()
.replace(/([ -_]|^)(.)/g, function (allMatches, firstMatch, secondMatch) {
return (firstMatch ? " " : "") + secondMatch.toUpperCase();
}
);
}
var eraser = document.getElementById("clear");
eraser.addEventListener('click', deleteEntry);
</script>
I hope to find the simpler and least invasive solution to complete a code that just have this left.
I would change your dropdown and input to the semantic html datalist element:
<label for="ice-cream-choice">Choose a flavor:</label>
<input list="ice-cream-flavors" id="ice-cream-choice" name="ice-cream-choice" />
<datalist id="ice-cream-flavors">
<option value="Chocolate">
<option value="Coconut">
<option value="Mint">
<option value="Strawberry">
<option value="Vanilla">
</datalist>
Then both search and keyboard accessibility should work more or less out of the box.
If you really don't want to do that, you have to attach event listeners (vanilla js) to the different elements of your dropdown and input field and write a rather long thing to be able to tab or arrow key your way down and up and back into the search field. I would say it's too much work compared to the reward.
Better to use some time to css-animate the datalist so it behaves a bit smoother and style it neatly.
I am using bracket editor when I save the bill.js editor show some
error at every document the desired output is not coming.
HTML code is
<!DOCTYPE html>
<html lang="en">
<head>
<title>split Bill</title>
<link rel="stylesheet" type="text/css" href="normalize.css">
<link rel="stylesheet" type="text/css" href="splitbill.css">
</head>
<body>
<div id="container">
<h1>Bill calculator</h1>
<div id="calculator">
<form>
<label>
How Much your Bill ? <br>
Rupees <input type="text" id="billAmount">
</label>
<label>
How was your Service sir?<br>
<select id="serviceFeedback">
<option disabled selected value="0">
--Choose an option--
</option>
<option value="0.4">
40% -Very Good
</option>
<option value="0.3">
30% - Good
</option>
<option value="0.2">
20% - it was Ok
</option>
<option value="0.1">
10% - Bad
</option>
<option value="0.05">
5% - poor
</option>
</select>
</label>
<label>
How many people sharing the bill?<br>
<input type="text" id="totalpeople">
people
</label>
<button type="button" id="calculate">calculate!</button>
</form>
</div>
<div id="totalTip">
<sup>Rupees</sup><span id="tip">0.00 </span>
<small id="each">each</small>
</div>
</div>
<script type="text/javascript" src="bill.js"></script>
</body>
</html>
javascript is here I didn't get desired output at every document function there is error sign please tell me what I do I am using bracket editor.
why I got this I am using
at the end of HTML code
//create function
function calculateTip() {
var billAmount = document.getElementById("billAmount").value;
var serviceFeedback = document.getElementById("serviceFeedback").value;
var numpeople =document.getElementById("totalpeople").value;
//validation
if (billAmount =="" ||serviceFeedback == 0) {
window.alert("please enter some value Boss!");
return;
}
//if input is empty
if (numpeople =="" ||numpeople <= 1) {
numpeople =1;
document.getElementById("each").style.display ="none";
} else {
document.getElementById("each").style.display ="block";
}
var total = (billAmount * serviceFeedback) / numpeople;
total = Math.round(total * 100) / 100;
total = total.toFixed(2);
//display the tip
document.getElementById("totalTip").style.display = "block";
document.getElementById("tip").innerHTML = total;
}
// hide tip amount
document.getElementById("totalTip").style.display ="none";
document.getElementById("each").style.display ="none";
//clicking the button calls our custom function
document.getElementById("calculate").onclick=function()
{
calculateTip();
}
In the function "calculateTip" I found the line:
if (billAmount =="" || ServiceFeedback == 0) {
Here ServiceFeedback starts with a capital letter instead of a lower case letter.
The selected option of a select-Field you get like that:
let selectElement = document.getElementById("serviceFeedback");
let serviceFeedback = selectElement.option[selectElement.selectedIndex].value;
In the html file I found an other problem:
<input type="text" id="totalpeople ">
There is a blank at the end of the id! Better would be:
<input type="text" id="totalpeople">
In the javascript file there is an other blank:
document.getElementById("each").style.display = " none";
Better would be:
document.getElementById("each").style.display = "none";
I hope that helps.
To ReferenceError: document is not defined I found that:
ReferenceError: document is not defined (in plain JavaScript)
=> My questions are:
What does bill.js contain?
Where is calculateTip() called?
I mean: Is anywhere a call like that document.getElementsBy... before the document is created?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Parallel Array Lookup II</title>
<script>
window.onload=initialize();
function initialize()
{
// do this only if the browser can handle DOM methods
if (document.getElementById)
{
aRegionalOffices = ["New York", "Chicago", "Houston", "Portland"];
aRegionalManagers = ["Shirley Smith", "Todd Gaston", "Leslie Jones",
"Harold Zoot"];
aRegOfficeQuotas = [300000, 250000, 350000, 225000];
// point to the critical input fields & save in global variables
oSelect = document.getElementById('offices');
oManager = document.getElementById('manager');
oQuota = document.getElementById('quota');
// if they all exist...
if (oSelect && oManager && oQuota)
{
// build the drop-down list of regional offices
for (var i = 0; i < aRegionalOffices.length; i++)
{
oSelect.options[i] = new Option(aRegionalOffices[i]);
}
// set the onchange behavior
//addEvent(oSelect, ‘change’, getData);
oSelect.addEventListener('change',getData);
}
// plug in data for the default select option
getData();
}
}
function getData(evt)
{
// get the offset of the selected option
var index = oSelect.selectedIndex;
// get data from the same offset in the parallel arrays
oManager.value = aRegionalManagers[index];
oQuota.value = aRegOfficeQuotas[index];
}
</script>
</head>
<body>
<h1>Parallel Array Lookup</h1>
<form id="officeData" action="" method="post">
<p>
<label for="offices">Select a regional office:</label>
<select id="offices" name="offices">
</select>
</p> <p>
<label for="manager">The manager is:</label>
<input type="text" id="manager" name="manager" size="35" />
</p>
<p>
<label for="quota">The office quota is:</label>
<input type="text" id="quota" name="quota" size="8" />
</p> </form>
</body>
</html>
Here I am trying to display regional manager names and their office quotas when user select any regional offices .
But while selecting regional office ,no option is coming and it is telling that cannot read property of SelectedIndex null. Here I have created three arrays for storing regional offices ,regionalMangers and office quotas values .
I am then making use of for loop for adding regional office value as option inside select tag.
window.onload= function_name (avoid writing function_name();)
Hope this will work
you have done mistake window.onload=initialize; or you can use following code also
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Parallel Array Lookup II</title>
<script>
var states = new Array();
states['India'] = new Array('ttttt', 'eeeee', 'aaaa', 'qqqq');
function setStates() {
var newOptions=states['India'];
var newValues=states['India'];
selectField = document.getElementById("state");
selectField.options.length = 0;
for (i=0; i<newOptions.length; i++)
{
selectField.options[selectField.length] = new Option(newOptions[i], newValues[i]);
}
}
</script>
</head>
<body onload="setStates();">
<h1>Parallel Array Lookup</h1>
<form id="officeData" action="" method="post">
<p>
<label>State :</label>
<select style="width:auto;" name="state" id="state">
<option value="">Please select a Country</option>
</select><br>
</p> <p>
<label for="manager">The manager is:</label>
<input type="text" id="manager" name="manager" size="35" />
</p>
<p>
<label for="quota">The office quota is:</label>
<input type="text" id="quota" name="quota" size="8" />
</p> </form>
</body>
</html>
just allocate which function would be invocated,
so "window.onload = initialize" is right way
I have created a codepen for you, where your select box is running. Also, I have fixed some code practices you have followed.
Hope this helps.
(function() {
var aRegionalOffices = ["New York", "Chicago", "Houston", "Portland"];
var aRegionalManagers = [
"Shirley Smith",
"Todd Gaston",
"Leslie Jones",
"Harold Zoot"
];
var aRegOfficeQuotas = [300000, 250000, 350000, 225000];
var oSelect = document.getElementById("offices");
if (oSelect) {
// build the drop-down list of regional offices
for (var i = 0; i < aRegionalOffices.length; i++) {
oSelect.options[i] = new Option(aRegionalOffices[i]);
}
oSelect.addEventListener("change", getData);
}
var getData = function(evt) {
var index = 0;
index = document.getElementById("offices").selectedIndex;
console.log(index);
document.getElementById("manager").value = aRegionalManagers[index];
document.getElementById("quota").value = aRegOfficeQuotas[index];
};
getData();
})();
Code snippet here
I have a drop-down menu that I am dynamically adding options to (based on an AJAX call) on an onfocus event. For some reason, the first time I click on the box, the options appear condensed into a tiny box, but the second time it works just fine. Does anyone know what might be causing this phenomenon? (Note: Because it involves AJAX, I can't insert a fiddle that could simulate the error, but I will post the code itself)
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Remove Class | IMS</title>
<link rel="stylesheet" type="text/css" href="../css/form.css"/>
</head>
<body>
<form>
<label for="class">Class:</label>
<select name="class" onfocus="loadClasses(this)" id="drop" required>
<option>Sample Value</option>
</select>
<hr/>
<button type="button" onclick="sendData()">Remove Class</button>
</form>
</body>
</html>
JS Code:
function genDrop(e, json) {
e.innerHTML = "";
var data = eval("({data: " + json + "})");
data = data.data;
for (var i = 0; i < data.length; i++) {
var option = data[i];
var o = document.createElement("option");
o.value = option.id;
o.innerHTML = option.name;
o.setAttribute("descript", option.descript);
o.style.width = "500px !important"
o.style.maxWidth = "200%";
e.appendChild(o);
}
}
function loadClasses(e) {
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
if (http.readyState === 4 && http.status === 200) {
genDrop(e, http.responseText);
}
}
http.open("GET", "getclasses.php", true);
http.send();
}
Use onload instead of onfocus
<select name="class" onload="loadClasses(this)" id="drop" required>
<option>Sample Value</option>
</select>
when the 1st (destination) and 2nd (attraction or activity) dropdown lists are selected the options the 3rd drop down list shows the available activities or attractions dynamically.
here is the demo : http://codepen.io/foolishcoder7721/pen/jWYOxm
my mark up:
<div class="multi-field-wrapper">
<button type="button" class="add-field">Add Destination</button>
<div class="multi-fields">
<div class="multi-field">
<select class="text-one" name="destination[]">
<option selected value="base">Please Select</option>
<option value="colombo">Colombo</option>
</select>
<br />
<select class="text-two" name="attraction_or_activity[]">
<option value="attraction_or_activity">Select the attractions or activities</option>
<option value="attraction">Attraction</option>
<option value="activity">Activity</option>
</select>
<select id="populated_attr_or_activity" name="attraction_or_activity_selected[]">
<!-- here I ahve to populate the ARRAYS as option -->
<option value="available_attr_act">Available attractions / activities</option>
</select>
</div>
</div>
And the jQuery for that:
<script>
$(document).ready(function() {
$(".text-two").change(function() { // when the attraction_OR_activity dropdown is selected
$('#populated_attr_or_activity').html(''); // emptying the selections of 3rd dropdown list if there was any selections were made before.
/* saving selected values in variables */
var selected_destination = $('.text-one :selected').val();
var selected_attraction_or_activity = $('.text-two :selected').val();
colombo_attractions = new Array("Ganga Ramaya","National Art Gallery","Galle Face Green","Arcade Indepentent Square");
colombo_activities = new Array("City Walk 2016","Traditional Dance Competition 2016","Local Spicy food");
if ( selected_destination == 'colombo' && selected_attraction_or_activity == 'attraction') {
colombo_attractions.forEach(function(t) {
$('#populated_attr_or_activity').append('<option>'+t+'</option>');
});
}
if ( selected_destination == 'colombo' && selected_attraction_or_activity == 'activity') {
colombo_activities.forEach(function(t) {
$('#populated_attr_or_activity').append('<option>'+t+'</option>');
});
}
});
</script>
That part works perfectly.
Now I want to a add more (add destination) button to create another set same dropdown lists. so guests can select more than one attractions and the activity.
For that I've added following jQuery part to the script.
<script>
/* ADD DESTINATION */
$('.multi-field-wrapper').each(function() {
var $wrapper = $('.multi-fields', this);
var x = 1;
$(".add-field", $(this)).click(function(e) {
x++;
$($wrapper).append('<div class="multi-field"><select class="text-one'+x+'" name="destination[]"><option selected value="base">Please Select</option><option value="colombo">Colombo</option><option value="kandy">Kandy</option><option value="anuradhapura">Anuradhapura</option></select><br/><select class="text-two'+x+'" name="attraction_or_activity[]"><option value="attraction_or_activity">Select the attractions or activities</option><option value="attraction">Attraction</option><option value="activity">Activity</option></select><select id="populated_attr_or_activity'+x+'" name="attraction_or_activity_selected[]"><option value="available_attr_act">Available attractions / activities</option></select>Remove</div>');
});
$($wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
});
</script>
I am able to get a set of same dropdown list when I click the <button type="button" class="add-field">Add Destination</button>
Remove also works fine.
You can check the demo : http://codepen.io/foolishcoder7721/pen/jWYOxm
but the issue is I am unable load the 'availble attraction/activities' on the 2nd or 3rd set of drop down list.
I think it's because of same variable NAME I am using in selected_destination and selected_attraction_or_activity.
var selected_attraction_or_activity+x gives me error.
how can make it work?
What I have to change to generate dynamic variables and arrays to load the available attractions / activities in 3rd dropdown in the set of 2nd and 3rd dynamically generated dropdown list according to the options selected?
Try modifying your code as below,
HTML:
<div class="multi-field-wrapper">
<button type="button" class="add-field">Add Destination</button>
<div class="multi-fields">
<div class="multi-field">
<select class="text-one" name="destination[]">
<option selected value="base">Please Select</option>
<option value="colombo">Colombo</option>
</select>
<br />
<select class="text-two" name="attraction_or_activity[]">
<option value="attraction_or_activity">Select the attractions or activities</option>
<option value="attraction">Attraction</option>
<option value="activity">Activity</option>
</select>
<!--input id="attr_acti_btn" type="button" value="Click to Show!" /-->
<select class="populated_attr_or_activity" name="attraction_or_activity_selected[]">
<!-- here I ahve to populate the ARRAYS as option -->
<option value="available_attr_act">Available attractions / activities</option>
</select>
</div>
<br/>
<!--div id="myDiv"></div>
<div id="attr_or_act_div"></div>
<!--a href="#" class="remove_field">Remove</a-->
</div>
Javascript:
$(document).ready(function () {
$(document).on('change', '.text-two', function () { // when the attraction_OR_activity dropdown is selected
var destination = $(this).parents('.multi-field');
$(destination).find('.populated_attr_or_activity').html(''); // emptying the selections of 3rd dropdown list if there was any selections were made before.
/* saving selected values in variables */
var selected_destination = $(destination).find('.text-one :selected').val();
var selected_attraction_or_activity = $(destination).find('.text-two :selected').val();
colombo_attractions = new Array("Ganga Ramaya", "National Art Gallery", "Galle Face Green", "Arcade Indepentent Square");
colombo_activities = new Array("City Walk 2016", "Traditional Dance Competition 2016", "Local Spicy food");
if (selected_destination == 'colombo' && selected_attraction_or_activity == 'attraction') {
colombo_attractions.forEach(function (t) {
$(destination).find('.populated_attr_or_activity').append('<option>' + t + '</option>');
});
}
if (selected_destination == 'colombo' && selected_attraction_or_activity == 'activity') {
colombo_activities.forEach(function (t) {
$(destination).find('.populated_attr_or_activity').append('<option>' + t + '</option>');
});
}
});
/* ADD DESTINATION */
$('.multi-field-wrapper').each(function () {
var $wrapper = $('.multi-fields', this);
var x = 1;
$(".add-field", $(this)).click(function (e) {
x++;
$($wrapper).append('<div class="multi-field"><select class="text-one" name="destination[]"><option selected value="base">Please Select</option><option value="colombo">Colombo</option><option value="kandy">Kandy</option><option value="anuradhapura">Anuradhapura</option></select><br/><select class="text-two" name="attraction_or_activity[]"><option value="attraction_or_activity">Select the attractions or activities</option><option value="attraction">Attraction</option><option value="activity">Activity</option></select><select class="populated_attr_or_activity" name="attraction_or_activity_selected[]"><option value="available_attr_act">Available attractions / activities</option></select>Remove</div>');
});
$($wrapper).on("click", ".remove_field", function (e) { //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
});
https://jsfiddle.net/2am152en/
<body>
<div id='main'>
Number: <input type="text" class="nums"/><br/>
</div>
<button id="more">Add More</button>
<button id="result">Resut</button>
<p><b>Total:</b>0</p>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#more').on('click',function(e){
var textFied = 'Number: <input type="text" class="nums"/><br/>';
$('#main').append(textFied);
});
$('#result').on('click',function(e){
var nums = $('.nums'),total = 0;
$(nums).each(function(index, el) {
total+=$(el).val()*1;
});
$('p').html('<b>Total:</b>'+total);
});
});
</script>
</body>
Demo: https://jsfiddle.net/rampukar/5n1j3ehr/
Output: