I've made a fictional hotel website that shows you hotel details when you click on a button.


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] + "<br />");

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] + "<br />");

Is there an easier way to code this? I'm just learning so I just did what I could.


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.

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];
   // 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

  • \$\begingroup\$ This is an excellent answer and I'm just in the middle of implementing it, but my code uses buttons, and when clicked they call the function. How do I call the function with the arguement? \$\endgroup\$
    – Addioioi
    Sep 23 '14 at 9:43
  • \$\begingroup\$ No worries, figured it out in the end! implementing the pictures was quite hard! jsfiddle.net/addiosamigo/dqdeL6m4/3 \$\endgroup\$
    – Addioioi
    Sep 23 '14 at 10:15
  • \$\begingroup\$ Looks good and it works fine! \$\endgroup\$
    – Michel
    Sep 23 '14 at 12:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.