I am having 1 Array in which my Source and Destination are like this:
markers.push({
"Location": "Chicago",
"IsLocation": "Yes"
});
markers.push({
"Location": "Los Angeles",
"IsLocation": "Yes"
});
Now when i will create points with my dynamic textbox then i would
like to add those all points in between source and destination.
Scenario 1:1st dynamic textbox with input say for Eg:abc
markers[0]:Chicago
markers[1]:abc
marker[2]:Los Angeles.
Scenario 2:2nd dynamic textbox with input say for Eg:pqr
markers[0]:Chicago
markers[1]:abc
markers[2]:pqr
marker[3]:Los Angeles.
Scenario 3:3rd dynamic textbox with input say for Eg:lmn
markers[0]:Chicago
markers[1]:abc
markers[2]:pqr
markers[3]:lmn
marker[4]:Los Angeles.
My first position will be fixed.
Code:
// Code goes here
var cnt = 1;
var maxNumberOfTextboxAllowed = 5;
var autocomplete = [];
var markers = [];
markers.push({
"Location": "Chicago",
"IsLocation": "Yes"
});
markers.push({
"Location": "Los Angeles",
"IsLocation": "Yes"
});
function Generatetextbox() {
if (cnt <= maxNumberOfTextboxAllowed) {
var fieldWrapper = $("<div class='fieldwrapper' id='field" + cnt + "'/>");
var fName = $("<input type='text' class='fieldname' id='Txtopt" + cnt + "' name='TxtoptNm" + cnt + "' />");
fieldWrapper.append(fName);
fieldWrapper.append('<br />');
fieldWrapper.append('<br />');
$("#abc").append(fieldWrapper);
var newInput = [];
var newEl = document.getElementById('Txtopt' + cnt);
var txtboxId = 'Txtopt' + cnt;
newInput.push(newEl);
setupAutocomplete(autocomplete, newInput, 0, txtboxId);
cnt = cnt + 1;
} else
alert("Cant create more than 5 textbox")
}
function setupAutocomplete(autocomplete, inputs, i, txtboxId) {
autocomplete.push((txtboxId));
var idx = autocomplete.length - 1;
document.getElementById(autocomplete[idx]).addEventListener("change", function() {
alert(document.getElementById(autocomplete[idx]).value);
var autoTextbox = [{
"Location": document.getElementById(autocomplete[idx]).value,
"IsLocation": "Yes"
}]
var markerLastIndexData = [{
"Location": markers[markers.length - 1].Location,
"IsLocation": "Yes"
}]
markers[markers.length - 1] = autoTextbox;
markers[markers.length] = markerLastIndexData;
console.log(markers)
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="abc"></div>
<button onclick="Generatetextbox()" class="btn btn-primary" type="button">Add</button>
You can check in console.I am getting not proper result.
Getting output like this:
Console output coming undefine:
Expected Output are shown in my scenarios like:
marker[0]:{
Location="Chicago",
Isolcation="Yes"
}
marker[1]:{
Location="abc",
Isolcation="Yes"
}
etc......
It's happening because in the setupAutocomplete function you're assigning an Array instead of an Object to the markers Array. Just remove the []'s on the lines where you the declare the two variables that are going to be pushed to the markers array.
Related
Is there a way to grab the values from the radio buttons? say it gets populated in the radio button and the options are Abuelos, Boogie Burger, Pad Thai, Coalition Pizza, Wild Eggs. Is there a way I can pull those values out and have it print out after hitting a submit button?
I also don't want the value to be redirected to another page. I just want it to print out below the submit button. I also don't want the user to be able to select a value after they hit the submit button
I am trying to make a voting poll where options are taken from multiple arrays and then someone can pick a value from the radio button and hit a submit button with their option printed out. That way the user can tell what they voted for.
part of the HTML code:
<form action="" id="food-form"></form>
Javascript code:
var mexicanFood = ["Caliente Mexican", "Abuelos", "Luciana's"],
asianFood = ["Omoni Korean", "Super Bowl Pho", "Sichuan Chinese", "Tian Fu Asian Bistro"],
americanFood = ["Boogie Burger", "City Barbeque", "The North End BBQ", "Wolfies Grill", "Bubs", "Fire on the Monon"];
pizza = ["Coalition Pizza", "Mackenzie River Pizza, Grill & Pub", "Bazbeaux Pizza", "Mellow Mushroom"]
thaiFood = ["Pad Thai", "Jasmine Thai", "Thai Orchid"]
notCategory = ["Jamaican Reggae Grill", "Mudbugs", "Yats", "Kolache Factory", ]
breakfast = ["Wild Eggs", "Egg and I", "Another Broken Egg Cafe", "Cafe Patachou"]
function createRandomArray(arraySize) {
var allFoods = mexicanFood.concat(asianFood).concat(americanFood).concat(pizza).concat(thaiFood).concat(notCategory).concat(breakfast),
randomFoods = [];
if (arraySize <= allFoods.length) {
randomFoods = [
mexicanFood[getRandomArrayIndex(mexicanFood)],
asianFood[getRandomArrayIndex(asianFood)],
americanFood[getRandomArrayIndex(americanFood)],
pizza[getRandomArrayIndex(pizza)],
thaiFood[getRandomArrayIndex(thaiFood)],
notCategory[getRandomArrayIndex(notCategory)],
breakfast[getRandomArrayIndex(breakfast)]
]; // at least one from each
// remove the ones that were initially added from each
allFoods.splice(allFoods.indexOf(randomFoods[0]), 1);
allFoods.splice(allFoods.indexOf(randomFoods[1]), 1);
allFoods.splice(allFoods.indexOf(randomFoods[2]), 1);
for (var i = 0; i < arraySize - 3; i++) {
var randomIndex = getRandomArrayIndex(allFoods);
randomFoods.push(allFoods[randomIndex]);
allFoods.splice(randomIndex, 1);
}
return randomFoods;
}
return allFoods; // requesting more items of food than the amount available, so just add them all
}
function getRandomArrayIndex(array) {
return Math.floor(Math.random() * array.length);
}
var randomFoods = createRandomArray(5);
for (var i = 0; i < randomFoods.length; i++) {
document.getElementById('food-form').innerHTML += '<input type="radio" name="food" value="' + randomFoods[i] + '"> ' + randomFoods[i] + '<br>';
}
You can use document.querySelector('input[name=food]:checked').value to get the selected value.
var mexicanFood = ["Caliente Mexican", "Abuelos", "Luciana's"],
asianFood = ["Omoni Korean", "Super Bowl Pho", "Sichuan Chinese", "Tian Fu Asian Bistro"],
americanFood = ["Boogie Burger", "City Barbeque", "The North End BBQ", "Wolfies Grill", "Bubs", "Fire on the Monon"];
pizza = ["Coalition Pizza", "Mackenzie River Pizza, Grill & Pub", "Bazbeaux Pizza", "Mellow Mushroom"]
thaiFood = ["Pad Thai", "Jasmine Thai", "Thai Orchid"]
notCategory = ["Jamaican Reggae Grill", "Mudbugs", "Yats", "Kolache Factory", ]
breakfast = ["Wild Eggs", "Egg and I", "Another Broken Egg Cafe", "Cafe Patachou"]
function createRandomArray(arraySize) {
var allFoods = mexicanFood.concat(asianFood).concat(americanFood).concat(pizza).concat(thaiFood).concat(notCategory).concat(breakfast),
randomFoods = [];
if (arraySize <= allFoods.length) {
randomFoods = [
mexicanFood[getRandomArrayIndex(mexicanFood)],
asianFood[getRandomArrayIndex(asianFood)],
americanFood[getRandomArrayIndex(americanFood)],
pizza[getRandomArrayIndex(pizza)],
thaiFood[getRandomArrayIndex(thaiFood)],
notCategory[getRandomArrayIndex(notCategory)],
breakfast[getRandomArrayIndex(breakfast)]
]; // at least one from each
// remove the ones that were initially added from each
allFoods.splice(allFoods.indexOf(randomFoods[0]), 1);
allFoods.splice(allFoods.indexOf(randomFoods[1]), 1);
allFoods.splice(allFoods.indexOf(randomFoods[2]), 1);
for (var i = 0; i < arraySize - 3; i++) {
var randomIndex = getRandomArrayIndex(allFoods);
randomFoods.push(allFoods[randomIndex]);
allFoods.splice(randomIndex, 1);
}
return randomFoods;
}
return allFoods; // requesting more items of food than the amount available, so just add them all
}
function getRandomArrayIndex(array) {
return Math.floor(Math.random() * array.length);
}
var randomFoods = createRandomArray(5);
for (var i = 0; i < randomFoods.length; i++) {
document.getElementById('food-form').innerHTML += '<input type="radio" name="food" value="' + randomFoods[i] + '"> ' + randomFoods[i] + '<br>';
}
function print() {
var t = document.querySelector('input[name=food]:checked');
if (t == null)
console.log('No value selected');
else
console.log(t.value);
}
<form action="" id="food-form">
</form>
<input type="submit" id="btn" value="Submit" onClick="print()">
I've created a JSON file to call out the name of a list of beers to display ABV and country but I am unable to display the results on the webpage. I was able to get the select tag to drop down the list, but when selecting a beer, it will only show the selected results as "undefined."
Here is the JS code I have so far...
var $select = $("#beerListing");
var beer = Array();
var country = Array();
$.getJSON("data.json", function(data) {
$select.html('');
for (var i = 0; i < data['beer'].length; i++)
$select.append('<option id="' + data["beer"][i]['id'] + '">' + data["beer"][i]["beer_name"] + '</option>');
for (x in data) {
if (beer.indexOf(data[x].beer_name) < 0) {
var y = beer.length;
beer[y] = data[x].beer_name;
country[y] = data[x].brewery_country;
}
}
showBeerList();
});
function showBeerList() {
var select = document.getElementById('beerListing');
for (var i = 0; i < beer.length; i++) {
var obj = document.createElement("option");
obj.text = beer[i];
obj.value = i;
select.appendChild(obj);
}
}
function getBeerInfo(picked) {
if (picked == "Pick Your Poison...") {
location.reload();
} else {
document.getElementById("name").innerHTML = beer[picked];
document.getElementById("country").innerHTML = country[picked];
}
}
HTML:
<html>
<head></head>
<body>
<h1>LCBO API TESTING</h1>
<select name="beerlist" id="beerListing" class="form-control" onchange="getBeerInfo(this.value)">
</select>
<br>
<label>Name:</label>
<label id="name">--</label>
<br>
<label>Country:</label>
<label id="country">--</label>
<br>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="main.js"></script>
</body>
</html>
JSON List called data.json
{
"beer": [{
"beer_name": "Organic Devon Cider",
"brewery_name": "Luscombe Organic Drinks",
"beer_type": "Cider",
"beer_abv": "4.9",
"beer_ibu": "0",
"comment": "",
"venue_name": "The Anchor & Hope",
"venue_city": "London",
"venue_state": "Greater London",
"brewery_country": "England"
}, {
"beer_name": "Beer A",
"brewery_name": "Beer A",
"beer_type": "Cider",
"beer_abv": "4.9",
"beer_ibu": "0",
"comment": "",
"venue_name": "Beer",
"venue_city": "New York",
"venue_state": "New York",
"brewery_country": "USA"
}]
}
You seemed to be adding the options to the select element twice and using for-in which iterates properties, not entries in an array.
Below snippet will not work as requires external data source.
var $select = $("#beerListing") ;
var beer = Array();
var country = Array();
$.getJSON("data.json", function(data) {
$select.html('');
for (var i = 0; i < data.beer.length; i = i + 1) {
if (beer.indexOf(data.beer[i].beer_name) < 0) {
beer.push(data.beer[i].beer_name);
country.push(data.beer[i].brewery_country);
}
}
showBeerList();
}
function showBeerList() {
var select = document.getElementById('beerListing');
for (var i = 0; i < beer.length; i++) {
var obj = document.createElement("option");
obj.text = beer[i];
obj.value = i;
select.appendChild(obj);
}
}
function getBeerInfo(picked) {
if (picked == "Pick Your Poison...") {
location.reload();
}
else {
document.getElementById("name").innerHTML = beer[picked];
document.getElementById("country").innerHTML = country[picked];
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>LCBO API TESTING</h1>
<select name="beerlist" id="beerListing" class="form-control" onchange="getBeerInfo(this.value)">
</select>
<br>
<label>Name:</label>
<label id="name">--</label>
<br>
<label>Country:</label>
<label id="country">--</label>
<br>
I got it working here: https://jsfiddle.net/bu7pkb5f/1/
What are you doing with:
if (beer.indexOf(data[x].beer_name) < 0) {
var y = beer.length;
beer[y] = data[x].beer_name;
country[y] = data[x].brewery_country;
}
I don't understand it but it's creating a third item in the list after the two real beer entries are processed. I left it commented out in the fiddle so you can check it out for yourself.
In firebug console 10 paragraphs is displayed in the source code of the page, but only the first one contains text.
It looks like the loop inserted the text each time into the same paragraph, overwriting it's value. How to insert the text into each paragraph?
(function(){
var names = ["Yaakov", "John", "Jen", "Jason", "Paul",
"Frank", "Larry", "Paula", "Laura", "Jim"];
for (var name in names) {
var new_par = document.createElement("p");
new_par.id = "new_par";
var greeter = document.getElementById("greeter");
greeter.appendChild(new_par);
var firstChar = names[name].charAt(0).toLowerCase();
if (firstChar === 'j') {
//byeSpeaker.speak(names[name]);
document.getElementById("new_par").innerHTML = "Goodbye" + " " + names[name];
} else {
//helloSpeaker.speak(names[name]);
document.getElementById("new_par").innerHTML = "Hello" + " " + names[name];
}
}
})();
Here's the HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Module 4 Solution Starter</title>
</head>
<body>
<h1>Module 4 Solution Starter</h1>
<div id="greeter"></div>
<script src="SpeakHello.js"></script>
<script src="SpeakGoodBye.js"></script>
<script src="script.js"></script>
</body>
</html>
The problem is that you are creating ten nodes with the same id, new_par, so you are always getting a reference to the first #new_par when you do
document.getElementById("new_par").innerHTML
The simplest solution will be to use the reference you already have, no need to call getElementById.
new_par.innerHTML = ...
The problem is that each paragraph has the same id. I added a counter variable, to add at the end of id...
(function(){
var counter = 0;
var names = ["Yaakov", "John", "Jen", "Jason", "Paul",
"Frank", "Larry", "Paula", "Laura", "Jim"];
for (var name in names) {
var new_par = document.createElement("p");
var par_id = "new_par" + counter;
new_par.id = par_id;
var greeter = document.getElementById("greeter");
greeter.appendChild(new_par);
var firstChar = names[name].charAt(0).toLowerCase();
if (firstChar === 'j') {
//byeSpeaker.speak(names[name]);
document.getElementById(par_id).innerHTML = "Goodbye" + " " + names[name];
} else {
//helloSpeaker.speak(names[name]);
document.getElementById(par_id).innerHTML = "Hello" + " " + names[name];
}
counter++;
}
})();
I have a problem alerting out 2 arrays on same line in Javascript. The user should write Movie name and movie rating(1-5) 5 times, and printMovies() function should print out users (movie)name and (movie)rating in a single line something like this:
Movie Rating
Star Wars 5
Lord of the Rings 4
Casino 4
Movie4 3
Movie5 2
How do I alert out all of five inputs in a single line (movie + rating) per line, AFTER they have got input from user?
//CODE
var title;
var rating;
var a = [];
var movies = [];
var ratings = [];
function buttonAddMovie()//Button onclick
{
addMovie(title, rating)
addMovie(title, rating)
addMovie(title, rating)
addMovie(title, rating)
addMovie(title, rating)
}
function addMovie(title, rating) {
do{
title = prompt("Enter movie: ");
}
while (title == "");
do {
rating = parseInt(prompt("Enter rating 1-5 on movie " + (title)));
}
while (rating > 5 || rating < 1);
movies.push(title);//Pushing title to movies
a.push(movies);//Pushing movies to a array
ratings.push(rating);//Pushing rating to ratings
a.push(ratings);//Pushing ratings to a array
printMovies()
}
function printMovies() {
for (var i = 0; i < a.length; i++) {
alert(a[0][0] + " " + a[0][1]);//Here is my biggest problem!
}
}
You problem is in the addMovie function your push the array to array. that means structure of the a is
a = [['title'] , ['rating'] , ['title','title1'],['rating',ratting1],......]
Try this with json object.
var movies = [];
function addMovie(title, rating) {
var movie = {};
do {
title = prompt("Enter movie: ");
}
while (title == "");
do {
rating = parseInt(prompt("Enter rating 1-5 on movie " + (title)));
}
while (rating > 5 || rating < 1);
movie.title = title;
movie.ratings = rating; movies.push(movie);
}
function printMovies() {
for (var i = 0; i < movies.length; i++) {
alert(movies[i].title + " " + movies[i].ratings);
}
}
function buttonAddMovie()//Button onclick
{
addMovie(title, rating);
addMovie(title, rating);
addMovie(title, rating);
addMovie(title, rating);
addMovie(title, rating);
printMovies();
}
<html>
<head>
<script>
var arr = [{
"Movie": "Movie1",
"Rating": 1
}, {
"Movie": "Movie2",
"Rating": 2
}, {
"Movie": "Movie3",
"Rating": 2
}, {
"Movie": "Movie5",
"Rating": 4
}, {
"Movie": "Movie4",
"Rating": 5
}, ];
var str = "";
for (var i = 0; i < arr.length; i++) {
str += "Movie Name: " + arr[i].Movie + " || Rating: " + arr[i].Rating + "\n";
}
alert( "Json Iterated Output \n" + str);
</script>
</head>
</html>
The reason it wasn't working was you had an array, a.
You pushed the movie name to 'a'
a = ['Movie name'];
But then you pushed the rating to 'a' separately
a = ['Rating'];
So the movie's name was replaced with rating, hence the alerts saying '(movie's name) undefined', then '(movie's rating) undefined'.
What I've done is removed the rating array and pushed the movie name and rating at the same time.
Also, I've changed the for loop to display the current movie by changing
alert(a[0][0] + " " + a[0][1]);
to
alert(a[i][0] + " " + a[i][1]);
otherwise it will always display the first movie rating.
var title;
var rating;
var a = [];
var movies = [];
function buttonAddMovie()//Button onclick
{
addMovie(title, rating, document.getElementById('quantity').value)
}
function addMovie(title, rating, amount) {
for(var count = 0; count < amount; count++){
do{
title = prompt("Enter movie: ");
}
while (title == "");
do {
rating = parseInt(prompt("Enter rating 1-5 on movie " + (title)));
}
while (rating > 5 || rating < 1);
movies.push(title,rating);//Pushing title to movies
a.push(movies);//Pushing movies to a array
movies = [];
}
printMovies();
}
function printMovies() {
for (var i = 0; i < a.length; i++) {
alert(a[i][0] + " " + a[i][1]);
document.getElementById('movielist').innerHTML+= "<li>"+a[i][0]+" - "+a[i][1]+"</li>"; // Adds movies to the <ul>
}
}
<h2>Add</h2>
<input id='quantity' placeholder='Amount of movies you want to add' /><br>
<button onclick='buttonAddMovie();'>Add Movies</button>
<h2>Movie list</h2>
<ul id='movielist'></ul>
Now you can stack as many as you want by writing the number in the input tag.
The movies are then displayed at the end in an unformatted list.
Very basic code, but I hope it helps.
I'm working on a quiz app, but I can't seem to get the value or the index of the radio buttons on the page.
Here's my code:
HTML:
<div id="container">
<div id="quiz"></div>
<div id="choices"></div>
<input id="next" type="button" value="Next">
<input id="back" type="button" value ="Back">
<div id="results"></div>
</div>
JavaScript:
var allQuestions = [
{
question: "Who is the best in the world?",
choices: ["CM Punk", "John Cena", "Daniel Bryan", "Roman Reigns"],
correctAnswer: 0
},
{
question: "Who is the current WWE World Champion?",
choices: ["John Cena", "Brock Lesnar", "Triple H"],
correctAnswer: 1
},
{
question: "Where is Toronto located?",
choices: ["Ontario", "California", "Georgia", "Texas"],
correctAnswer: 0
},
{
question: "What is the largest California city?",
choices: ["Los Angeles", "San Fransico", "San Deigo", "Anahiem"],
correctAnswer: 0
}
];
var quiz = document.getElementById('quiz');
var choicesContainer = document.getElementById('choices');
var nextButton = document.getElementById('next');
var backButton = document.getElementById('back');
var score = 0;
var questionIndex = 0;
// A function to show the question.
function showQuiz() {
var currentQuestion = allQuestions[questionIndex].question;
quiz.textContent = currentQuestion;
choicesContainer.innerHTML = "";
var choicesNum = allQuestions[questionIndex].choices.length;
for (var i = 0; i < choicesNum; i++) {
var choice = allQuestions[questionIndex].choices[i];
choicesHTML = "<input type='radio' name='choice'>" + choice + "</br>";
choicesContainer.innerHTML += choicesHTML;
}
}
function checkScore() {
//var correctAnswers = allQuestions[questionIndex].correctAnswer;
var radios = document.querySelectorAll('[type=radio]');
var userAnswers;
for (var i = 0; i < radios.length; i++) {
if(radios[i].checked) {
userAnswers = radios[i].value;
console.log(userAnswers);
}
}
}
showQuiz();
nextButton.addEventListener('click', function(){
questionIndex++;
showQuiz();
checkScore();
});
backButton.addEventListener('click', function(){
questionIndex--;
showQuiz();
});
First, I thought it was because I was calling the checkAnswers() function before the DOM was ready, but that doesn't seem the be the case so I'm stuck.
Any help, would be awesome and greatly appreciated. Thanks!
You have an error in your logic.
allQuestions[questionIndex] is undefined, when you click "next" after the last question. You need to check, if theres a question left.
and i think your selector for the radio buttons is wrong.
watch this:
javascript check radio buttons automatically
you need something like
radios = document.getElementsByTagName('INPUT');
for (var i = 0; i < radios.length; i++) {
if(radios[i].type == "radio"){
if(radios[i].checked) {
userAnswers = radios[i].value;
}
}
}
or you select only the checked element with
checkedbutton = document.querySelector("input[name='choice']:checked");
and further: you should add the answers as "value" of the button, like
<input type="radio" name="choice" value="Ontario">
this way you can get the value easy with
checkedbutton.value;