Displaying random images from a folder on button click - javascript

I am pretty much brand new to web development, and I have been struggling to find the answers I need to make this work. I have a "random generator" that when you click on the button it displays some text. I used an array and a basic random math generator to make this work.
What I want to do is make the button display an image from a folder WITHOUT having to manually enter data into an array every time I want to update it. The list is constantly changing so it would be ideal to just be able to add and remove the images from the folder when it needs to be updated. I have found many pieces of what I am trying to do just by google searching, but I am struggling to put it all together to make it work.
My image directory would be images/commanders
This is what I have found to get random images from a folder but I just cant get it to work.
function getRandomImage(imgAr, path) {
path = path || 'images/'; // default path here
var num = Math.floor( Math.random() * imgAr.length );
var img = imgAr[ num ];
var imgStr = '<img src="' + path + img + '" alt = "">';
document.write(imgStr); document.close();
}
I don't know how helpful this is but for reference, this is my working Javascript
var commanders = [
'Brian Stoutarm',
'Aboshan, Cephalid Emperor',
'Adamaro, First to Desire',
'Adeliz, the Cinder Wind',
'Adriana, Captain of the Guard',
'Agrus Kos, Wojek Veteran',
'Akki Lavarunner',
'Alesha, Who Smiles at Death',
'Alexi, Zephyr Mage',
'Alhammarret, High Arbiter',
'Anax and Cymede',
'Anowon, the Ruin Sage',
'Anthousa, Setessan Hero',
'Arcanis the Omnipotent',
'Asmira, Holy Avenger',
'Atalya, Samite Master',
'Atarka, World Render',
'Atogatog',
'Avacyn, Guardian Angel',
'Azami, Lady of Scrolls',
'Baird, Steward of Argive',
'Balthor the Stout',
'Baru, Fist of Krosa',
'Basandra, Battle Seraph',
'Bladewing the Risen',
'Blind Seer',
'Borborygmos',
'Bosh, Iron Golem',
'Bounteous Kirin',
'Captain Lannery Storm',
'Celestial Kirin',
'Chromium',
'Chrous of the Conclave',
'Circu, Dimir Lobotomist',
'Cloudhood Kirin',
'Commander Greven il-Vec',
'Crosis, the Purger',
'Crovax the Cursed',
'Cunning Bandit',
'Dakkon Blackblade',
'Danitha Capashen, Paragon',
'Darigaaz, the Igniter',
'Daxos of Meletis',
'Daxos the Returned',
'Depala, Pilot Exemplar',
'Drana, Kalastria Bloodchief',
'Dromoka, the Eternal',
'Dwynen, Gilt-Leaf Daen',
'Emmara Tandris',
'Emmara, Soul of the Accord',
'Endrek Sahr, Master Breeder',
'Etrata, the Silencer',
'Evra, Halcyon Witness',
'Exava, Rakdos Blood Witch',
'Fumiko the Lowblood',
'Garna, the Bloodflame',
'Garza Zol, Plague Queen',
'General Tazri',
'Gerrard Capashen',
'Ghost Council of Orzhova',
'Glissa Sunseeker',
'Gonti, Lord of Luxury',
'Grand Warlord Radha',
'Greel, Mind Raker',
'Grunn, the Lonely King',
'Gwafa Hazid, Profiteer',
'Hakim, Loreweaver',
'Hallar, the Firefletcher',
'Hapatra, Vizier of Poisons',
'He Who Hungers',
'Heidar, Rimewind Master',
'Hisoka, Minamo Sensei',
'Hixus, Prison Warden',
'Horde of Notions',
'Horobi, Death\'s Wail',
'Hua Tuo, Honored Physician',
'Hythonia the Cruel',
'Iname as One',
'Iname, Death Aspect',
'Iname, Life Aspect',
'Infernal Kirin',
'Intet, the Dreamer',
'Isareth the Awakener',
'Isperia the Inscrutable',
'Ith, High Arcanist',
'Ixidor, Reality Sculptor',
'Izoni, Thousand-Eyed',
'Jalira, Master Polymorphist',
'Jareth, Leonine Titan',
'Jaya Ballard, Task Mage',
'Jazal Goldmane',
'Jedit Ojanen of Efrava',
'Jeleva, Nephalia\'s Scourge',
'Jeska, Warrior Adept',
'Jiwari, the Earth Aflame',
'Jodah, Archmage Eternal',
'Jolrael, Empress of Beasts',
'Jor Kadeen, the Prevailer',
'Jori En, Ruin Diver',
'Josu Vess, Lich Knight',
'Jushi Apprentice',
'Kalemne, Disciple of Iroas',
'Kamahl, Pit Fighter',
'Kambal, Consul of Allocation',
'Kami of the Crescent Moon',
'Kari Zev, Skyship Raider',
'Kaseto, Orochi Archmage',
'Kazarov, Sengir Pureblood',
'Kazuul, Tyrant of the Cliffs',
'Kefnet the Mindful',
'Kemba, Kha Regent',
'King Macas, the Gold-Cursed',
'Kiyomaro, First to Stand',
'Kodama of the Center Tree',
'Kodama of the North Tree',
'Kodama of the South Tree',
'Kopala, Warden of Waves',
'Kothophed, Soul Hoarder',
'Kumano, Master Yamabushi',
'Kuon, Ogre Ascendant',
'Kurkesh, Onakke Ancient',
'Kwende, Pride of Femeref',
'Kyoki, Sanity\'s Eclipse',
'Latullar, Keldon Overseer',
'Lavinia of the Tenth',
'Lavinia, Azorious Renegade',
'Lena, Selfless Champion',
'Linessa, Zephyr Mage',
'Lorthos, the Tidemaker',
'Lu Xun, Scholar General',
'Lyzolda, the Blood Witch',
'Mageta the Lion',
'Malfegor',
'Mannichi, the Fevered Dream',
'Marath, Will of the Wild',
'Maraxus of Keld',
'Marwyn, the Nurturer',
'Masumaro, First to Live',
'Mavren Fein, Dusk Apostle',
'Melek, Izzet Paragon',
'Mina and Denn, Wildborn',
'Mirko Vosk, Mind Drinker',
'Molimo, Maro-Sorcerer',
'Naban, Dean of Iteration',
'Nath of the Gilt-Leaf',
'Nefarox, Overlord of Grixis',
'Neheb, the Worthy',
'Nezumi Graverobber',
'Nikya of the Old Ways',
'Nin, the Pain Artist',
'Niv-Mizzet, Dracogenius',
'Niv-Mizzet, the Firemind',
'Noyan Dar, Roil Shaper',
'Odric, Master Tactician',
'Ojutai, Soul of Winter',
'Oros, the Avenger',
'Oviya Pashiri, Sage Lifecrafter',
'Oyobi, Who Split the Heavens',
'Padeem, Consul of Innovation',
'Padeem, Consul of Inovation',
'Palladia-Mors',
'Patron of the Akki',
'Patron of the Kitsune',
'Patron of the Nezumi',
'Pia Nalaar',
'Pianna, Nomad Captain',
'Purraj of Urborg',
'Radha, Heir of Keld',
'Raff Capashen, Ship\'s Mage',
'Raksha Golden Cub',
'Razia, Boros Archangel',
'Rishkar, Peema Renegade',
'Rona, Disciple of Gix',
'Roon of the Hidden Realm',
'Rorix Bladewing',
'Rosheen Meanderer',
'Rubinia Soulsinger',
'Sachi, Daughter of Seshiro',
'Samut, Voice of Dissent',
'Sek\'Kuar, Deathkeeper',
'Selvala, Explorer Returned',
'Shanna, Sisay\'s Legacy',
'Sharuum the Hegemon',
'Shimatsu the Bloodcloaked',
'Shisato, Whispering Hunter',
'Shu Yun, the Silent Tempest',
'Sidisi, Brood Tyrant',
'Silumgar, the Drifting Death',
'Silvos, Rogue Elemental',
'Skyfire Kirin',
'Slimefoot, the Stoaway',
'Slinn Voda, the Rising Deep',
'Sol\'kanar the Swamp King',
'Soramaro, First to Dream',
'Sosuke, Son of Seshiro',
'Squee, the Immortal',
'Sram, Senior Edificer',
'Starke of Rath',
'Stonebrow, Krosan Hero',
'Student of Elements',
'Surrak, the Hunt Caller',
'Sydri, Galvanic Genius',
'Sygg, River Guide',
'Szadek, Lord of Secrets',
'Tajic, Blade of the Legion',
'Tajic, Legion\'s Edge',
'Takeno, Samurai General',
'Talrand, Sky Summoner',
'Tatyova, Benthic Druid',
'Telim \'Tor',
'Temet, Vizier of Naktamun',
'Temmet, Vizier of Naktamun',
'Teneb, the Harvester',
'Teshar, Ancestor\'s Apostle',
'Tesya, Envoy of Ghosts',
'Tetsuko Umezawa, Fugitive',
'Tetzimoc, Primal Death',
'The Unspeakable',
'Thelon of Havenwood',
'Thriss, Nantuko Primus',
'Tiana, Ship\'s Caretaker',
'Tibor and Lumia',
'Torgaar, Famine Incarnate',
'Traxos, Scourge of Kroog',
'Triad of Fates',
'Tromokratis',
'Unesh, Criosphinx Sovereign',
'Urgoros, the Empty One',
'Uyo, Silent Prophet',
'Vaevictis Asmadi',
'Valduk, Keeper of the Flame',
'Varolz, the Scar-Striped',
'Verdeloth the Ancient',
'Visara the Dreadful',
'Volrath the Fallen',
'Vorel of the Hull Clade',
'Whisper, Blood Liturgist',
'Wort, the Raidmother',
'Wydwen, the Biting Gale',
'Xira Arien',
'Yargle, Glutton of Urborg',
'Yasova Dragonclaw',
'Yisan, the Wanderer Bard',
'Zada, Hedron Grinder',
'Zahid, Djinn of the Lamp',
'Zegana, Utopian Speaker',
'Zurgo Helmsmasher',
'Zndrsplt, Eye of Wisdom',
'Okaun, Eye of Chaos',
'Virtus the Veiled',
'Gorm the Great',
'Khorvath Brightflame',
'Sylvia Brightspear',
'Tawnos, Urza\'s Apprentice',
'Fblthp, the Lost',
'Massacre Girl',
'Krenko, Tin Street Kingpin',
'Neheb, Dreadhorde Champion',
'Mowu, Loyal Companion',
'Storrev, Devkarin Lich',
'Tolsimir, Friend to Wolves',
'Sisay, Weatherlight Captain',
'Pashalik Mons',
'Ayula, Queen Among Beers',
'Sephara, Sky\'s Blade',
'Atemsis, All-Seeing',
'Gargos, Vicious Watcher',
'Gerrard, Weatherlight Hero',
'Grismold, the Dreadsower',
'Rayami, First of the Fallen',
'Tahngarth, First Mate',
'Linden, Steadfast Queen',
'Syr Elenora, the Discerning',
'Syr Konrad, the Grim',
'Syr Carah, the Bold',
'Syr Farren, the Hengehammer',
'Yorvo, Lord of Garenbrig',
'Grumgully, the Generous',
'Daxos, Blessed by the Sun',
'Taranika, Akroan Veteran',
'Alirios, Enraptured',
'Callaphe, Beloved of the Sea',
'Thryx, the Sudden Storm',
'Aphemia, the Cacophany',
'Tymaret, Chosen from Death',
'Anax, Hardened in the Forge',
'Arasta of the Endless Web',
'Renata, Called to the Hunt',
'Atris, Oracle of Half-Truths',
'Dalakos, Crafter of Wonders',
'Eutropia, the Twice-Favored',
'Gallia of the Endless Dance',
'Haktos the Unscarred',
'Kunoros, Hound of Athreos',
'Siona, Captain of the Pyleas',
'Tomorrow, Azami\'s Familiar',
'Tatyova, Benthic Druid',
'Obzedat, Ghost Council',
'Tymaret, the Murder King',
'Godo, Bandit Lord',
'Arvad the Cursed',
'Ruric Thar, the Unbowed',
'Seton, Krosan Protector',
'Ayli, Eternal Pilgrim ',
'Aryel, Knight of Windgrace',
'Zo-Zu the Punisher',
'Munda, Ambush Leader',
'Kolaghan, the Storm\'s Fury',
'Darigaaz Reincarnated',
'Isperia, Supreme Judge',
'Mairsil, the Pretender',
]
function newCommander() {
var randomNumber = Math.floor(Math.random() * (commanders.length));
document.getElementById('commanderDisplay').innerHTML = commanders[randomNumber];
}
And this is my working HTML
<!DOCTYPE html>
<html>
<head>
<title>QFTJL Random Commander Generator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Quest for the Janklord Random Commander Generator</h1>
<button onclick="newCommander()"><img style="height:200px;width:200px" src="wheelmaster.png"></button>
<br> </br>
<script src="javascript.js"></script>
<font size="6">
<div id="commanderDisplay">
<!-- Commanders will display here -->
</div>
</font>
</body>
</html>
I apologize if I am asking this poorly. This is my first time posting a question. Any help would be magnificent! Thank you!

This should work.
In the image element creation part, insted of document.write try:
let image = document.createElement("img")
image.src = "src/filename.jpg"
let target = document.getElementById("target")
target.appendChild(image)
and put a blank
<div id="target"> </div>
where you want the image to appear.

Related

How do I change or update <p> tag data with every client request

there is my code,
if(data.country_name == 'India'){
$('.fact').append("<h2 id='india'>Fact about India</h2>");
$('.fact').append("<p>The world's highest cricket ground is in Chail, Himachal Pradesh. Built in 1893 after leveling a hilltop, this cricket pitch is 2444 meters above sea level.</p>");
$(.fact).append('<p>2</p>')
$(.fact).append('<p>3</p>')
$(.fact).append('<p>4</p>')
console.log('this a india');
} else if(data.country_name == 'Turkey'){
$('.fact').append("<h2 id='turkey'>Fact about Turkey</h2>");
$('.fact').append('<p>The story of Santa Claus originated in Turkey</p>');
}else if(data.country_name == 'Russia'){
$('.fact').append("<h2 id='russia'>Fact about Russia</h2>");
$('.fact').append('<p>Russia is home to some 20 percent of the world’s trees, and one-fifth of the world’s freshwater is in Lake Baikal.</p>');
}
now, if I add 4 <p> for India's fact in the class='fact', so whenever the client location is India, it needs to show 1 random <p> from the if statement
anyone can help, I make it complicated, I know it may be too simple!!
Just set up your facts as an array and use Math.random() with Math.floor() to pick a random one
if(data.country_name == 'India'){
$('.fact').append("<h2 id='india'>Fact about India</h2>");
let facts = [
"The world's highest cricket ground is in Chail, Himachal Pradesh. Built in 1893 after leveling a hilltop, this cricket pitch is 2444 meters above sea level.",
"fact2",
"fact3",
"fact4"];
$('.fact').append('<p>' + facts[Math.floor(Math.random()*facts.length)] + '</p>')
console.log('this a india');
// ...
You can cut down a lot of code repetition by adding some structure to the data in an object or array and look up what you need based on data.country.name
Something like:
const countries = {
'India': {
id: 'india',
title: 'Facts about India',
facts: ['I-1','I-2', 'I-3','I-4']
},
'Turkey': {
id: 'turkey',
title: 'Facts about Turkey',
facts: ['T-1','T-2', 'T-3','T-4']
}
}
const item = countries[data.country_name],
fact = item.facts[Math.floor(Math.random()*item.facts.length)],
$head = $('<h2>',{id: item.id, text: item.title}),
$p = $('<p>',{text: fact));
$('.fact').append($head, $p);

Adding media when javascript button is clicked

i have created a JS button that generates random facts when clicked.
now i want each String(fact) to have media below to make the fact more interesting and fun.
<script> <!-- arrays -->function GetValue(){ var myarray= new Array()
myarray[0]="your lungs are worth $58,200 each,heart will fetch $57,000, and your kidneys are good for another $91,400,your DNA will fetch more than 9M$,while your bone marrow, your most valuable possession, is worth $23 million all by itself. Therefore your body market value is exactly: $45,618,575.82."
myarray[1]="Hans Langseth the man with the world's longest beard 5.33 m (17 ft 6 in)tripped on his long beard. He lost his balance and fell, breaking his neck from the unexpected accident! He died instantaneously."
myarray[2]="A Sesame Street episode (ep. 847) was aired on TV in 1976,it was so scary that the authorities had to pull it off due to several complaints from parents saying their children screamed in horror."<!--END-var random = myarray[Math.floor(Math.random() * myarray.length)];//alert(random); document.getElementById("fact button").innerHTML=random;}</script>
HTML:
<input type="button" id="fact_button" value="Fact Button" onclick="GetValue();" />
Assuming you want to show media like images, for instance, this is one way to do it:
window.onload = () => {
const factsArr = [
{
image: 'http://via.placeholder.com/350x150',
content: "your lungs are worth $58,200 each,heart will fetch $57,000, and your kidneys are good for another $91,400,your DNA will fetch more than 9M$,while your bone marrow, your most valuable possession, is worth $23 million all by itself. Therefore your body market value is exactly: $45,618,575.82."
},
{
image: 'http://via.placeholder.com/200x140',
content: "Hans Langseth the man with the world's longest beard 5.33 m (17 ft 6 in)tripped on his long beard. He lost his balance and fell, breaking his neck from the unexpected accident! He died instantaneously."
},
{
image: 'http://via.placeholder.com/200x100',
content: "A Sesame Street episode (ep. 847) was aired on TV in 1976,it was so scary that the authorities had to pull it off due to several complaints from parents saying their children screamed in horror."
}
];
document.getElementById('generate-btn').addEventListener('click', () => {
const idx = Math.floor(Math.random() * factsArr.length);
document.getElementById('random-fact-content').innerHTML = factsArr[idx].content;
document.getElementById('random-fact-image').setAttribute('src', factsArr[idx].image)
})
}
<button id="generate-btn">Generate Random Fact</button>
<div id="random-fact-content"></div>
<img id="random-fact-image"></img>

Combine Arrays from different variables to populate randomly javascript

I am trying to recreate a "Today's Special" menu so that every time the page is refreshed, a different type of pizza will populate, but with the correct properties within the arrays. So the 0 indexed data all belong together, and the 1 indexed belong together, etc. Here is my code that I tried, but it populates randomly from any random variable. Please help.
I want it to look like: "Today's Special: pizzaName + price + description"
var pizzaName = ['Four Loop', 'Conditional Love', 'The DOM','Conjunction Function'];
var price = [44.44, 22.14, 16.99, 17.02];
var description = ['Spin your wheel with this quattro cheese mix doused in garlic and truffle oil. Loop there it is!', 'This island favorite doesn\'t give you a chance to say no. Korean bulgogi meat, kim chee, mozzarella cheese and onions always returns true! Boo~Ya!', 'This dynamic blend of Duck, Olives and Mango will change your original thought of what a pizza should be. The only thing constant is change for this bad boy!', 'Create your own pie by passing in handpicked fresh ingredients. Invoke your appetite and creativity! Mamma Mia return back to glory!'];
HTML:
<section id="today">
<div class="content">
<h3 class="sectionTitle">Today's Special</h3>
<p id="special">Conditional Love</p>
</div>
</section>
JavaScript:
function randomPizzaFunction(hungry, hungrier, hungriest){
for(var i = 0; i<hungry.length; i++){
var displayTodaysSpecial = hungry.concat(hungrier).concat(hungriest);
console.log(displayTodaysSpecial[i]);
}
return displayTodaysSpecial;
}
randomPizzaFunction(pizzaName, price, description);
var genRandomPizza = randomPizzaFunction(pizzaName, price, description);
console.log(genRandomPizza);
var changeSpecial = document.getElementById("special");
changeSpecial.innerHTML = genRandomPizza[Math.floor(Math.random() * genRandomPizza.length)];
You should store your pizza properties together in one object per pizza, not spread over different arrays. Things become much easier when you use a different structure:
var pizzas = [{
name: 'Four Loop',
price: 44.44,
description:'Spin your wheel with this quattro cheese mix doused in garlic and truffle oil. Loop there it is!',
},{
name: 'Conditional Love',
price: 22.14,
description: 'This island favorite doesn\'t give you a chance to say no. Korean bulgogi meat, kim chee, mozzarella cheese and onions always returns true! Boo~Ya!',
},{
name: 'The DOM',
price: 16.99,
description: 'This dynamic blend of Duck, Olives and Mango will change your original thought of what a pizza should be. The only thing constant is change for this bad boy!',
},{
name: 'Conjunction Function',
price: 17.02,
description: 'Create your own pie by passing in handpicked fresh ingredients. Invoke your appetite and creativity! Mamma Mia return back to glory!'
}];
function randomPizza(pizzas){
return pizzas[Math.floor(Math.random() * pizzas.length)];
}
var pizza = randomPizza(pizzas);
document.getElementById("special-name").textContent = pizza.name;
document.getElementById("special-price").textContent = pizza.price;
document.getElementById("special-description").textContent = pizza.description;
<section id="today">
<div class="content">
<h3 class="sectionTitle">Today's Special</h3>
<div id="special">
Special: <span id="special-name"></span><br>
Price: $<span id="special-price"></span><br>
<span id="special-description"></span>
</div>
</div>
</section>
You could build an array with objects
[
{
name: "Four Loop",
price: 44.44,
description: "Spin your wheel with this quattro cheese mix doused in garlic and truffle oil. Loop there it is!"
},
{
name: "Conditional Love",
price: 22.14,
description: "This island favorite doesn't give you a chance to say no. Korean bulgogi meat, kim chee, mozzarella cheese and onions always returns true! Boo~Ya!"
},
{
name: "The DOM",
price: 16.99,
description: "This dynamic blend of Duck, Olives and Mango will change your original thought of what a pizza should be. The only thing constant is change for this bad boy!"
},
{
name: "Conjunction Function",
price: 17.02,
description: "Create your own pie by passing in handpicked fresh ingredients. Invoke your appetite and creativity! Mamma Mia return back to glory!"
}
]
and take it for random choice.
Then make an output with the properties of the chosen pizza.
function getRandomPizza(pizza) {
return pizza[Math.floor(Math.random() * pizza.length)];
}
var pizzaName = ['Four Loop', 'Conditional Love', 'The DOM', 'Conjunction Function'],
price = [44.44, 22.14, 16.99, 17.02],
description = ['Spin your wheel with this quattro cheese mix doused in garlic and truffle oil. Loop there it is!', 'This island favorite doesn\'t give you a chance to say no. Korean bulgogi meat, kim chee, mozzarella cheese and onions always returns true! Boo~Ya!', 'This dynamic blend of Duck, Olives and Mango will change your original thought of what a pizza should be. The only thing constant is change for this bad boy!', 'Create your own pie by passing in handpicked fresh ingredients. Invoke your appetite and creativity! Mamma Mia return back to glory!'],
pizza = pizzaName.map(function (a, i) {
return { name: a, price: price[i], description: description[i] };
}),
randomPizza = getRandomPizza(pizza);
['name', 'price', 'description'].forEach(function (k) {
document.getElementById(k).innerHTML = randomPizza[k];
});
<div class="content">
<h3 class="sectionTitle">Today's Special</h3>
<h4 id="name"></h4>
<h4><span id="price"></span> $</h4>
<p id="description"></p>
</div>
In html I took the libertiy and added element for 'name , price and description' along with id
<section id="today">
<div class="content">
<h3 class="sectionTitle">Today's Special</h3>
<h1 id='name'>pizza name</h1>
<h2 id='price'>price</h2>
<p id='dec'>description</p>
</div>
you just need to get a random number and then access each array and populate every element respectively
var pizzaName = ['Four Loop', 'Conditional Love', 'The DOM','Conjunction Function'];
var price = [44.44, 22.14, 16.99, 17.02];
var description = [
'Spin your wheel with this quattro cheese mix doused in garlic and truffle oil. Loop there it is!',
'This island favorite doesn\'t give you a chance to say no. Korean bulgogi meat, kim chee, mozzarella cheese and onions always returns true! Boo~Ya!',
'This dynamic blend of Duck, Olives and Mango will change your original thought of what a pizza should be. The only thing constant is change for this bad boy!',
'Create your own pie by passing in handpicked fresh ingredients. Invoke your appetite and creativity! Mamma Mia return back to glory!'
];
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
var rn = getRandomInt(0,3)
document.getElementById('name').innerHTML = pizzaName[rn]
document.getElementById('price').innerHTML = price[rn]
document.getElementById('desc').innerHTML = description[rn]
I'm assuming that you have your script tag at the end of the page .. if not wrap the code in a document.ready method .
#trincot is correct, you should store it in array of objects. Like this
var pizza = [{
name: 'Four Loop',
price: 44.44,
description: 'Spin your wheel with this quattro cheese mix doused in garlic and truffle oil. Loop there it is!'
}, {
name: 'Conditional Love',
price: 22.14,
description: 'This island favorite doesn\'t give you a chance to say no. Korean bulgogi meat, kim chee, mozzarella cheese and onions always returns true! Boo~Ya!'
}];
var display = pizza[Math.floor(Math.random() * pizza.length)];

Javascript - using match to find two words and return all text between them (in spite of line breaks)

I'm a pure amateur when it comes to programming, and javascript in particular, but I'm trying to work out a problem and I haven't had any luck finding a solution through extensive Google search.
I'm writing a short script to take a block of text that is copied from a website that always has a consistent format/layout, but different results, and paste it into large text field. Then you click a button and it extracts certain pieces of information from the text, and presents that information in a reformatted way.
I got it to work for a large part of what I want to do, but one section of the text includes multiple line breaks, and my match isn't working as a result. When this match fails it breaks the rest of it as well. Specifically I'm trying to pull the restaurant name, address, city & zip, and phone number from between the words "Restaurant:" and "Cuisine:" in the below text:
Guest Name: John Doe Phone: (555) 555-5555 Reservation Date: Saturday, March 14, 2015 Time: 6:00 PM Party Size: 2 Confirmation #: 1703515901 Restaurant: Café Boulud
20 East 76th St.
New York, NY 10021
(212) 772-2600
Cuisine: French, American Message from the Restaurant: Thank you for making reservations at Cafe Boulud. FOR INTERNATIONAL GUESTS: Please leave your email address and full phone number in the space above. This information will be used to confirm your reservation with us. Our menu offers a wide range of a la carte options inspired by Chef Daniel Boulud's four culinary muses: la tradition, classic French cuisine; la saison, seasonal delicacies; le potager, the vegetable garden; and le voyage, the flavors of world cuisines.
Here's what I have written. It works for all of the reservation details, but not the restaurant details:
<HTML>
<HEAD>
<script>
function getVal(){
var val = document.getElementById('ta').value;
reserved = val.match("Name: (.*) Phone:");
date = val.match("Date: (.*) Time:");
time = val.match("Time: (.*) Party");
party = val.match("Size: (.*) Confirmation");
confirmation = val.match("#: (.*) Restaurant:");
restaurant = val.match("Restaurant: (.*) Cuisine:");
}
function myFunction() {
var myWindow = window.open("", "myWindow", "width=400, height=400");
myWindow.document.write(restaurant[1]+"</p>"+"Reserved Under: "+reserved[1]+"</br>Date: "+
date[1]+" at "+time[1]+"</br>Party Size: "+party[1]+"</br>Confirmation #: "+confirmation[1]
);
}
</script>
</HEAD>
<BODY>
</p>
<form>
<textarea rows="30" cols="100" id="ta"></textarea></br>
<button onclick="getVal(); myFunction();">Get Value</button>
</form>
</BODY>
</HTML>
If you want to match EVERY single character, you have to do something like [\s\S]* instead of .*.
In your case, your regex should be "Restaurant: (\s\S*)Cuisine:"
If I get it right, there is no space before "Cuisine" because there is a line break.
Demo :
Restaurant: ([\s\S]*)Cuisine:
Debuggex Demo
HTML Live example :
function getVal(){
var val = document.getElementById('ta').value;
reserved = val.match("Name: (.*) Phone:");
date = val.match("Date: (.*) Time:");
time = val.match("Time: (.*) Party");
party = val.match("Size: (.*) Confirmation");
confirmation = val.match("#: (.*) Restaurant:");
restaurant = val.match(/Restaurant: ([\s\S]*)Cuisine:/);
}
getVal();
document.getElementById('result').innerHTML = "Restaurant : " +restaurant[1]+"\n"+"Reserved Under: "+reserved[1]+"\nDate: "+
date[1]+" at "+time[1]+"\nParty Size: "+party[1]+"\nConfirmation #: "+confirmation[1];
#ta, #result
{
width:100%;
height:200px;
}
<h2>Text to parse :</h2>
<textarea id="ta">
Guest Name: John Doe Phone: (555) 555-5555 Reservation Date: Saturday, March 14, 2015 Time: 6:00 PM Party Size: 2 Confirmation #: 1703515901 Restaurant: Café Boulud
20 East 76th St.
New York, NY 10021
(212) 772-2600
Cuisine: French, American Message from the Restaurant: Thank you for making reservations at Cafe Boulud. FOR INTERNATIONAL GUESTS: Please leave your email address and full phone number in the space above. This information will be used to confirm your reservation with us. Our menu offers a wide range of a la carte options inspired by Chef Daniel Boulud's four culinary muses: la tradition, classic French cuisine; la saison, seasonal delicacies; le potager, the vegetable garden; and le voyage, the flavors of world cuisines.
</textarea>
<hr>
<h2>Result :</h2>
<textarea id="result">
</textarea>

Cannot pull correct data from a Javascript array into an HTML form

I am trying to return the description value of the corresponding author name and book title(that are typed in the text boxes). The problem is that the first description displays in the text area no matter what.
<h1>Bookland</h1>
<div id="bookinfo">
Author name:
<input type="text" id="authorname" name="authorname"></input><br />
Book Title:
<input type="text" id="booktitle" name="booktitle"></input><br />
<input type="button" value="Find book" id="find"></input>
<input type="button" value="Clear Info" id="clear"></input><br />
<textarea rows="15" cols="30" id="destin"></textarea>
</div>
JavaScript:
var bookarray = [{Author: "Thomas Mann", Title: "Death in Venice", Description: "One of the most famous literary works of the twentieth century, this novella embodies" + "themes that preoccupied Thomas Mann in much of his work:" + "the duality of art and life, the presence of death and disintegration in the midst of existence," + "the connection between love and suffering and the conflict between the artist and his inner self." },
{Author: "James Joyce", Title: "A portrait of the artist as a young man", Description: "This work displays an unusually perceptive view of British society in the early 20th century." + "It is a social comedy set in Florence, Italy, and Surrey, England." + "Its heroine, Lucy Honeychurch, struggling against straitlaced Victorian attitudes of arrogance, narroe mindedness and sobbery, falls in love - while on holiday in Italy - with the socially unsuitable George Emerson." },
{Author: "E. M. Forster", Title: "A room with a view", Description: "This book is a fictional re-creation of the Irish writer'sown life and early environment." + "The experiences of the novel's young hero,unfold in astonishingly vivid scenes that seem freshly recalled from life" + "and provide a powerful portrait of the coming of age of a young man ofunusual intelligence, sensitivity and character. " },
{Author: "Isabel Allende", Title: "The house of spirits", Description: "Allende describes the life of three generations of a prominent family in Chile and skillfully combines with this all the main historical events of the time, up until Pinochet's dictatorship." },
{Author: "Isabel Allende", Title: "Of love and shadows", Description: "The whole world of Irene Beltran, a young reporter in Chile at the time of the dictatorship, is destroyed when" + "she discovers a series of killings carried out by government soldiers." + "With the help of a photographer, Francisco Leal, and risking her life, she tries to come up with evidence against the dictatorship." }]
function searchbook(){
for(i=0; i < bookarray.length; i++){
if ((document.getElementById("authorname").value & document.getElementById("booktitle").value ) == (bookarray[i].Author & bookarray[i].Title)){
document.getElementById("destin").value =bookarray[i].Description
return bookarray[i].Description
}
else {
return "Not Found!"
}
}
}
document.getElementById("find").addEventListener("click", searchbook, false)
Your code got html escaped for some reason, but I think the problem is in your if. Regardless, this should give you your answer and be slightly faster since it doesn't try to look up the elements in the dom inside a loop
function searchbook(){
var author = document.getElementById('authorname').value;
var title = document.getElementById('booktitle').value;
for (var i=0, book; book = bookarray[i]; i++) {
if (book.Title == title && book.Author == author) {
return book.Description;
}
}
return "Not Found"
}
This code is a bit more flexible and will populate your textarea for you.
function searchbook(){
var author = document.getElementById("authorname").value;
var book = document.getElementById("booktitle").value;
for(i=0; i < bookarray.length; i++){
if(bookarray[i].Author.match(author) || bookarray[i].Title.match(book))
{
document.getElementById("destin").value = bookarray[i].Description;
break;
}
}
}
I'm not sure why you're using a textarea if there's no user input to be had on that particular element.

Categories

Resources