patternjavascriptMinor
Fictional Hotel Website
Viewed 0 times
hotelwebsitefictional
Problem
I've made a fictional hotel website that shows you hotel details when you click on a button.
jsFiddle
Is there an easier way to code this? I'm just learning so I just did what I could.
jsFiddle
var hotel = {Name: "Park Hotel", Price: "£120.00", Rooms: 50}
var hotel2 = {name: "West End", price: "£240.00", rooms: 150}
el_p = document.getElementById("para1");
el_picture = document.getElementById("picture");
el_picture2 = document.getElementById("picture2");
function showPrice() {
el_picture2.style.display = "none";
el_picture.style.display = "block";
el_p.innerHTML = " ";
for(details in hotel) {
el_p.innerHTML += (details += ": " + hotel[details] + "");
}
}
function showPrice2() {
el_picture.style.display = "none";
el_picture2.style.display = "block";
el_p.innerHTML = " ";
for(details in hotel2) {
el_p.innerHTML += ( details += ": " + hotel2[details] + "");
}
}Is there an easier way to code this? I'm just learning so I just did what I could.
Solution
What if you have 167 hotels? Would you copy/paste the code for all those hotels? I don't think you would.
Start with making the script more general, so you have only to feed the data into the function.
(make sure you use the same keys all the time")
Now you can feed that into a function:
Inside the function you have all the elements you need to display the hotel information. Replace the content of all the elements (give your divs id's!) like name, price, rooms and the picture.
If you want to display a hotel, call the function with
Start with making the script more general, so you have only to feed the data into the function.
var hotel=new Array;
hotel[1] = {Name: "Park Hotel", Price: "£120.00", Rooms: 50, pict: "pict1"}
hotel[2] = {Name: "West End", Price: "£240.00", Rooms: 150, pict: "pict2}(make sure you use the same keys all the time")
Now you can feed that into a function:
function showHotel(hotelnumber){
var hoteldata=hotel[hotelnumber];
document.getElementById['name'].innerHTML=hoteldata['Name'];
document.getElementById['price'].innerHTML=hoteldata['Price'];
// etc etc etc
}Inside the function you have all the elements you need to display the hotel information. Replace the content of all the elements (give your divs id's!) like name, price, rooms and the picture.
If you want to display a hotel, call the function with
showHotel(11);Code Snippets
var hotel=new Array;
hotel[1] = {Name: "Park Hotel", Price: "£120.00", Rooms: 50, pict: "pict1"}
hotel[2] = {Name: "West End", Price: "£240.00", Rooms: 150, pict: "pict2}function showHotel(hotelnumber){
var hoteldata=hotel[hotelnumber];
document.getElementById['name'].innerHTML=hoteldata['Name'];
document.getElementById['price'].innerHTML=hoteldata['Price'];
// etc etc etc
}showHotel(11);Context
StackExchange Code Review Q#63365, answer score: 6
Revisions (0)
No revisions yet.