1

I'm kinda new to html/javascript. I wanted to store the user input value in array (already done this part) and display it into HTML table(I'm stuck at this one). When user press the button, the table will show up at the bottom.

Here's my code so far: HTML

<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
  <script class="jsbin" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
</head>
<body>
  <form>
    <h1>Please enter data</h1>
    <input id="title" type="text" placeholder="Title" />
    <input id="name" type="text" placeholder="Name" />
    <input id="tickets" type="text" placeholder="Tickets" />
    <input type="button" value="Save/Show" onclick="insert()" />
  </form>
  <div id="display"></div>
</body>
</html>

This is my Javascript code:

var titles  = [];
var names   = [];
var tickets = [];

var titleInput  = document.getElementById("title");
var nameInput   = document.getElementById("name");
var ticketInput = document.getElementById("tickets");

var messageBox  = document.getElementById("display");

function insert ( ) {
 titles.push( titleInput.value );
 names.push( nameInput.value );
 tickets.push( ticketInput.value );

 clearAndShow();
}

function clearAndShow () {
  // Clear our fields
  titleInput.value = "";
  nameInput.value = "";
  ticketInput.value = "";

  // Show our output
  messageBox.innerHTML = "";

  messageBox.innerHTML += "<tr>Titles</tr>" + titles.join(" ") + "<td></td>";
  messageBox.innerHTML += "<tr>Name</tr> <td>" + names.join(" ") + "</td>";
  messageBox.innerHTML += "<tr>tickets</tr> <td>" + tickets.join(" ")+ "</td>";
}

I can't display the array into the tables. I'm quite new to Javascript/HTML so any help would be appreciated. :D

Bluesky Izz
  • 45
  • 1
  • 7

3 Answers3

2

As I have already commented, you will have to loop over array and compute html and set it. Your function clearAndShow will set last value only.

I have taken liberty to update your code. You should not save data in different arrays. Its better to use one array with proper constructed object.

JSFiddle

var data = [];
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");

var messageBox = document.getElementById("display");

function insert() {
  var title, name, ticket;
  title = titleInput.value;
  name = nameInput.value;
  ticket = ticketInput.value;
  data.push({
    title: title,
    name: name,
    ticket: ticket
  });
  clearAndShow();
}

function clearAndShow() {
  // Clear our fields
  titleInput.value = "";
  nameInput.value = "";
  ticketInput.value = "";
  messageBox.innerHTML = computeHTML();
}

function computeHTML() {
  var html = "<table>";
  console.log(data)
  data.forEach(function(item) {
    html += "<tr>";
    html += "<td>" + item.title + "</td>"
    html += "<td>" + item.name + "</td>"
    html += "<td>" + item.ticket + "</td>"
    html += "</tr>";
  });
  html += "</table>"
  return html;
}
article,
aside,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<head>
  <script class="jsbin" src=""></script>
  <script class="jsbin" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>

  <body>
    <form>
      <h1>Please enter data</h1>
      <input id="title" type="text" placeholder="Title" />
      <input id="name" type="text" placeholder="Name" />
      <input id="tickets" type="text" placeholder="Tickets" />
      <input type="button" value="Save/Show" onclick="insert()" />
    </form>
    <div id="display"></div>
  </body>
Rajesh
  • 24,354
  • 5
  • 48
  • 79
  • Thanks @Rajesh! You rock! Thanks for helping! – Bluesky Izz Mar 23 '16 at 17:23
  • One quick question... If I wanted to make a table header for title and name and tickets, how can I do that? I've tried modified your code to put the table header, and I still can't make it work.... @Rajesh – Bluesky Izz Mar 23 '16 at 18:22
  • @Bluesky Izz Instead of `var html = "";` you can write `var html = "
    ";` to get the header section of the table on there. After the foreach loop instead of having `html += "
    TitleNameTicket
    "` you can write `html += ""` to close off the body section of the table.
    – goodface87 Mar 23 '16 at 18:35
1

Please try and change your js code like below, not the most elegant but a start:

function clearAndShow () {
  // Clear our fields
  titleInput.value = "";
  nameInput.value = "";
  ticketInput.value = "";

  // Show our output
  messageBox.innerHTML = "";
  messageBox.innerHTML += "<tr>";
  messageBox.innerHTML += "<td>Titles</td>";
  messageBox.innerHTML += "<td>Name</td>";
  messageBox.innerHTML += "<td>Tickets</td>";
  messageBox.innerHTML += "</tr>";
  for(i = 0; i <= titles.length - 1; i++)
  {
    messageBox.innerHTML += "<tr>";
    messageBox.innerHTML += "<td>" + titles[i]+ "</td>";
    messageBox.innerHTML += "<td>" + names[i] + "</td>";
    messageBox.innerHTML += "<td>" + tickets[i]+ "</td>";
    messageBox.innerHTML += "</tr>";
  }
}

and your display html like so:

<table id="display"></table>

have a look at fiddle over here https://jsfiddle.net/gvanderberg/cwmzyjf4/

The data array in Rajesh's example is the better option to go for.

  • 1
    Its not a good practice to manipulate DOM in loop. Better way is to create HTML string and then perform bulk operation. – Rajesh Mar 23 '16 at 17:22
  • Thanks!! I'll take a look over it first. Thanks for the suggestion too! – Bluesky Izz Mar 23 '16 at 17:22
  • @Rajesh, agreed, as I said, not the most elegant solution but didn't want to change the original code too much. – Gareth van der Berg Mar 23 '16 at 17:23
  • @Rajesh Why is that? – goodface87 Mar 23 '16 at 17:24
  • 1
    @goodface87 This should be a good reference point. [But why's the browser DOM still so slow after 10 years of effort?](http://stackoverflow.com/questions/6817093/but-whys-the-browser-dom-still-so-slow-after-10-years-of-effort). In general, when you update DOM, it has to build DOM tree again, render css and many other tasks. So its better to perform bulk operation – Rajesh Mar 23 '16 at 17:26
  • @Rajesh Awesome. Thank you! – goodface87 Mar 23 '16 at 17:31
0

you deleted your last question about the numbering of authors, but I wrote a big answer to you for it. Just for you to have it :

Wow, man you have several problems in your logic.

First, you have to specify to your form not to submit when you click on one or the other submit buttons (Add a book, or Display book) :

<form onsubmit="return false;">

Second, you have to define your numbering var to 0 and use it when you want to assign a number to a book :

var numbering = 0;

Then, in your addBook function, you have to use that global numbering variable to set you no variable :

function addBook() {
  numbering++; // increments the number for the books (1, 2, 3, etc)
  var no, book, author;
  book = bookInput.value;
  author = nameInput.value;
  no = numbering;
  ...
}

Then you have all kind of mistakes like double ";" on certain lines etc.

A huge mistake is also done on your code when you use "forEach". Notice this function only works when you use jQuery library ! You have to include it before you use it :

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

An other huge mistake you do is that your "Display" button has the id "display" and your messageBox also has this id. This is forbidden because when you want to use the element which has this ID, Javascript won't know which of the two is the good one. So rename your button id in displayAuthors :

<input type="submit" id="displayAuthors" value="Display" onclick="displayBook()" />

Now, what you also can do, is to call your displayBooks function everytime you add a new book like this :

function addBook() {
  numbering++;
  var no, book, author;
  book = bookInput.value;
  author = nameInput.value;
  no = numbering;

  data.push({
    book: book,
    author: author,
    no: no
  });

  displayBook();
}

So I did all these things here on CodePen : https://codepen.io/liorchamla/pen/JMpoxM


The JQuery solution

Here you used the basics of Javascript (called Vanilla JS) which is very cool because you have to learn it, but I also wrote you a CodePen to show you how you could have done this with jQuery :-)

Here it is : http://codepen.io/liorchamla/pen/oxwNwd

Basicly, the javascript changed to this :

$(document).ready(function(){
  var data = []; // data is an empty array

  // binding the addBook button with the action :
  $('#addBook').on('click', function(){
    var book = {
      title: $('#bookname').val(),
      author: $('#authors').val(),
      // note we won't use a numbering variable
    };
    data.push(book);

    // let's automaticly trigger the display button ? 
    $('#displayBooks').trigger('click');
  });
  // binding the displayBooks button with the action :
  $('#displayBooks').on('click', function(){
    $('#display').html(computeHTML());
  });

  function computeHTML(){
    // creating the table
    html = "<table><tr><th>No</th><th>Book</th><th>Author</th></tr>";
    // for each book in the data array, we take the element (book) and the index (number)
    data.forEach(function(element, index){
      // building the table row, note that index starts at 0, so we increment it to have a start at 1 if it is 0, 2 if it is 1 etc.
      html += "<tr><td>" + parseInt(index++) + "</td><td>" + element.title + "</td><td>" + element.author + "</td></tr>";
    })
    html += "</table>";
    // returning the table
    return html;
  }
})

You might find it complicated, but with time you will see that jQuery helps a lot !

They are lot of things we could enpower in this script but this is a good starting, don't you think ?

Cheers from Marseille, France !

Lior CHAMLA
  • 128
  • 8
  • Thanks for the info. I didn't yet learn about jQuery so I didn't quite understand your code. I've already got the answer for my question before so that's why I've deleted it. Turns out that I only ask a very stupid question lol. @Lior CHAMLA – Bluesky Izz Mar 26 '16 at 07:42