I'm having trouble with my code. I build this code but there is an issue that I cannot resolve myself. The code should work like this: When entering multiple data (name & email) the datas repeat from top to last.
For example I enter 3 names & emails one by one. I want an output of
Fred fred#gmail.com
George george#gmail.com
Laila laila#gmail.com
But instead I get this results in my table:
Fred fred#gmail.com
Fred fred#gmail.com
George George#gmail.com
Fred fred#gmail.com
George George#gmail.com
Laila laila#gmail.com
In the clearAndSave method in the end when you call $("#output").append(html); you should call $("#output").empty(); first to clear the previous results.
Change the method like this:
function clearAndSave() {
//...
$("#output").empty();
$("#output").append(html);
}
If you want to presist your initial data, modify the clearAndSave method like this:
function clearAndSave() {
// Clear fields
nameInput.value = "";
emailInput.value = "";
var html = [];
console.log(arraypeaople);
for(i = 0; x <= arraypeaople.length - 1; i++){
// Mark added rows to be able to remove them later
html += "<tr class='added-row'>";
html += "<td>" + arraypeaople[i].name + "</td>";
html += "<td>" + arraypeaople[i].email + "</td>";
html += "</tr>";
}
// Remove just the added rows
$("#output").find(".added-row").remove();
$("#output").append(html);
}
So I have a table with rows and columns that I loop through and an array which I split by spaces. What I am trying to do is if someone clicks parts[x] that information gets put into an input box.
var parts = data[j][i].split(' ');
tableData += '<td>';
for(x=0; x<parts.length; x++)
{
tableData += '' +parts[x] + ' ' + '';
}
tableData += '</td>';
For instance from below you can see the table that gets outputted now if someone was to press on Software I want Software to go to the top input box on the left which as you can tell already has Software in it for this example the input boxes name=a
Add a click listener to each tag like this:
var parts = data[j][i].split(' ');
tableData += '<td>';
for(x=0; x<parts.length; x++)
{
tableData += '' +parts[x] + ' ' + '';
}
tableData += '</td>';
Then define a handler outside of your tableData generation code like this:
function clickedPart(part){
document.getElementById("input_box").value = part.innerHTML
}
Please note I assumed your input box has the id "input_box". You can change that to whatever you want, but I recommend giving it an ID instead of a name.
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
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>
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.
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 !
I've created a bootstrap menu from a json response. The menu gets the list of items and creates a link to https://example.com/api/products/GetProductDetail/product_id which takes you to the json response.
What I need it to do is not follow the link to the json response, but rather get that response, parse the data and plug it into a div on the existing page, but I'm not sure how to do that.
Here is what I have right now:
<script>
$.getJSON('https://example.com/api/products/GetProductList/', function(data) {
var output = '<div class="panel panel-default">';
for (var i in data.Categories) {
output += '<div class="panel-heading '+data.Categories[i].category_id +'"><a data-toggle="collapse" data-parent="#accordion" href="#' + data.Categories[i].category_id + '-products">';
output += data.Categories[i].Category + '</a></div>';
output += '<div id="' + data.Categories[i].category_id + '-product" class="panel-collapse collapse"><div class="panel-body">';
for (var j in data.Categories[i].Products) {
output += '<li>'+data.Categories[i].Products[j].short_description + " -- " + data.Categories[i].Products[j].cost+' coins</li>';
}
output += "</div></div>";
}
output += "</div>";
document.getElementById("accordion").innerHTML = output;
});
</script>
Instead of creating a link to the product detail url, create a link to some function accepting the productid.
This function could make a call just like the one you currently have for the product list, processing the json and appending the result to a div.
So add a function like:
function getProduct(id) {
$.getJSON('https://example.com/api/products/GetProductDetail/' + id, function(data) {
//Process JSON to some HTML.
var productDetails = '<div>' + data.Product.Name + '</div>';
//Add it to the div where you want your product details to appear
document.getElementById("detailsDiv").innerHTML = productDetails;
};
}
and replace the li, created for every product in the overview with something like the following:
output += '<li><a onclick="getProduct(' + data.Categories[i].Products[j].product_id + ');">'+data.Categories[i].Products[j].short_description + " -- " + data.Categories[i].Products[j].cost+' coins</a></li>';
I have a javascript code that takes objects from json.
from this, i built an html string:
var htmlstr = "<table border=0>";
for (var i=0;i<jsonData.people.length;i++) {
htmlstr=htmlstr+"<tr><td>" + jsonData.people[i].name + "</td>";
htmlstr=htmlstr+"<td>"+ jsonData.people[i].cash + "</td>";
htmlstr=htmlstr+"<td><button onclick='changeCash(i)'>Update</button></td></tr>";
}
htmlstr=htmlstr+"</table>";
layer.addFeatures(features);
layer.events.on({ "featureselected": function(e) { updateMak('mak', htmlstr) } });
function changeCash(k) {
jsonData.people[k].cash=jsonData.people[k].cash+100;
}
The HTML page is as follows:
<script type="text/javascript">
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
alert("Mobile device detected."); }
function updateMak(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
} </script>
<div id="mak"> List of People </div>
Lets say this displays 10 people with their money.
If I click on one of their Update buttons, I think the json data is updated as intended. But I don't know how to verify it. The values in the form doesn't update the new value from the changeCash function.
How do I update the htmlstr and also update what's already displayed on screen?
Please advise.
When you generate htmlstr for the people cash
htmlstr=htmlstr+"<td>"+ jsonData.people[i].cash + "</td>";
You should also generate id for this td so that you can update the content from the function changeCash(k).
Something like
htmlstr=htmlstr+"<td id='peoplecash"+i+"'>" + jsonData.people[i].cash + "</td>";
And then in your changeCash function
function changeCash(k) {
jsonData.people[k].cash=jsonData.people[k].cash+100;
var peoplecash= document.getElementById("peoplecash"+k);
peoplecash.innerHTML = jsonData.people[k].cash;}