Click here to Skip to main content
15,309,768 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I created the array "arr" to take the guests name and number of guests from the and want to show in the window like this:
Guest's name: ......
Person number: ......
Here is my code and when I tried it it can't defined the value in the array. "guest_name" and "person_number" are the variables which take value from DOM input elements
<!DOCTYPE html>
<html lang="jp">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <p>Name:<input type="text" id="name"></p>
    <p>Number of person:<input type="text" id="number"></p>
    <button onclick="Reserve()">Reserve</button>
    <p><span id="guest_in"></span></p>
    <p><span id="wait_pair"></span></p>
    <p><span id="total_person"></span></p>
    <br><button onclick="Guide()">Guide</button>
    <p><span id="guest_out"></span></p>
        let arr = [];
        let guest_in = document.querySelector("#guest_in");
        let guest_number = document.querySelector("#number");
        function Reserve()
            let guest_name = document.querySelector("#name").value;
            let guest_num = document.querySelector("#number").value;
            let person_number = Number(guest_num);
            arr.push[{name:guest_name, number: person_number}];
            guest_in.innerHTML = `Guest's name: ${arr[0].guest_name}<br>number of 

What I have tried:

If I made the array simply like
 guest_in.innerHTML = arr;

Then it will displayed the name also the number every time I hit the button "Reserve" but it will not display the format I would like to do as above.
Updated 28-Jul-21 6:30am
SeeSharp2 27-Jul-21 13:48pm
You are confusing arrays and json. See

Or google for arrays of objects.

1 solution

Two problems:

1) Your arr.push call needs to use round brackets rather than square brackets:
arr.push({name:guest_name, number: person_number});

2) The object you've added to the array has properties called name and number, so you can't refer to the non-existent properties guest_name and guest_number. You need to use the correct property names:
guest_in.innerHTML = `Guest's name: ${arr[0].name}<br>number of guests:${arr[0].number}`;

As a bonus problem, you're always displaying the details of the first guest added to the array. Any subsequent guests will never be displayed.
Member 14629414 28-Jul-21 12:53pm
@Richard Deeming Thank you very much for your comment.As for the bonus problem I would delete the index[0] when call the properties as it specified only first item.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900