Making table with objects in array? - javascript

I'm a beginner in javascript and I have a little problem with my code. I found an exercise and i'm trying to do it. I have to write a function that will insert text from variable into table. I never met something like this. This variable looks like four objects in array. I want to show text in the table when I press a button. There are two buttons. When I press "Fizyka" button i should see:
Fizyka
Ola Kowal
Ela Nowak
and when I press "Chemia":
Chemia
Ala Goral
Ula Szpak
So this is my code. All i can edit is function show(study):
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8">
</head>
<body>
<button onclick="show('fizyka')">Fizyka</button>
<button onclick="show('chemia')">Chemia</button>
<div id="list"></div>
<script>
var student=[
{name:"Ola", second_name:"Kowal", study:"fizyka"},
{name:"Ela", second_name:"Nowak", study:"fizyka"},
{name:"Ala", second_name:"Goral", study:"chemia"},
{name:"Ula", second_name:"Szpak", study:"chemia"},
];
function show(study)
{
if (study==='fizyka')
{
document.getElementById("list").innerHTML = "<h2>student.kierunek</h2><ul><li>student.name + " " + student.second_name</li><li>student.name + " " + student.second_name</li></ul>";
}
if (study==='chemia')
{
document.getElementById("list").innerHTML = "<h2>student.kierunek</h2><ul><li>student.name + " " + student.second_name</li><li>student.name + " " + student.second_name</li></ul>";
}
}
</script>
</body>
</html>
It's not working. I don't know how to insert text from this variable into table.

There is several problem with your code. I have written piece of code which is working and you can use it and inspire.
<button onclick="show('fizyka')">Fizyka</button>
<button onclick="show('chemia')">Chemia</button>
<div id="list"><h2></h2><ul></ul></div>
<script>
//Student array
var student=[
{name:"Ola", second_name:"Kowal", study:"fizyka"},
{name:"Ela", second_name:"Nowak", study:"fizyka"},
{name:"Ala", second_name:"Goral", study:"chemia"},
{name:"Ula", second_name:"Szpak", study:"chemia"},
];
function show(study)
{
console.log('ENTER show('+study+')');
//Select h2 element
var header = document.getElementById("list").firstChild;
//Set h2 element text
header.innerHTML = study;
//Select ul element
var list = document.getElementById("list").lastChild;
//Set inner html to empty string to clear the content
list.innerHTML = "";
//loop through students and set the appropriate html element values
for(var i = 0; i < student.length; i++){
//check whether student[i] studies study which is put as a paramter into the function
if(student[i].study === study){
//Create new li element
var li = document.createElement('li');
//Into li element add a new text node which contains all data about the student
li.appendChild(document.createTextNode(student[i].name + ' ' + student[i].second_name));
//add li element into ul
list.appendChild(li);
}
}
console.log('LEAVE show('+study+')');
}
</script>

Related

JavaScript/HTML - Passing onclick button parameter to JavaScript function

I'm very new to JavaScript so I apologize if this question has an extremely obvious answer. What I'm trying to do is pass the name of a text box in HTML to a function in Javascript via an onclick button. The goal of the function is to test a given string and highlight it based on certain parameters (for my testing, it is simply length).
There are multiple weird odds and ends within the functions that I'm aware of and working on, I know the functions work as when I remove the parameters and call the code text box directly, it prints exactly what I expect it to. But I want to be able to pass multiple text boxes without needing a specific function per box.
The code I have is as follows. I've included all of it in case the mistake was made somewhere I didn't expect it to be.
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<label for="wordOne">Word One</label><br>
<input type="text" id="wordOne" name="wordOne"><br>
// Pass the value for the wordOne textbox to verify function
<button type="button" onclick="verify(wordOne,this)">Check</button><br><br>
<label for="wordTwo">Word Two</label><br>
<input type="text" id="wordTwo" name="wordTwo"><br>
// Pass the value for the wordTwo textbox to verify function
<button type="button" onclick="verify(wordTwo,this)">Check</button><br><br>
<p id="test"></p><br>
<p id="error"></p>
<script>
// Highlights any code in a given line.
function highlight(text,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
function verify(button,el){
var begin=1;
var end=1
var id="test";
var string = document.getElementById(button).value;
var len=string.length;
if(len>5)
{
document.getElementById(id).innerHTML = string +" "+len;
highlight(string,id,begin,end);
}
else
{
document.getElementById(id).innerHTML = string;
}
}
</script>
</body>
</html>
I apologize again if this is extremely obvious but I'm honestly not sure what I'm doing wrong. Thanks in advance for any help!
You can get the name of the textbox by the attribute
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
And then use it in your function as
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
function highlight(x,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
NOTE : By [0] it means the first one that is the first textbox.

button click, adds some text and number to a div. Doesn't work

I really need some help to create this order list. It's the mening that, when you click on the button it adds the text inside the addToList, to the div, so it shows up on the page. It should add the data (name, price), in javascript.
But can't get it to work properly.
<html>
<body>
<div id="myList">
</div>
<button onclick="addToList('donut', '25,-')">add</button>
</body>
</html>
<style>
#myList {
border: 1px solid black;
margin-bottom: 10px;
}
</style>
<script>
function displayListCart() {
var myList = document.getElementById("myList");
};
function addToList(name,price) {
var itemOrder = {};
//itemOrder with data
itemOrder.Name=name;
itemOrder.Price=price;
//Add newly created product to our shopping cart
listCart.push(itemOrder);
displayListCart();
}
</script>
Here is a Fiddle Demo.
I'm not a fan of inline calls to JavaScript functions because it violates separation of concerns, so I've changed the way the event is bound. This isn't part of your problem, but I'm using this approach:
HTML:
<div id="myList">
</div>
<button id="btn" data-name="donut" data-price="25,-">add</button>
Note:
I've added the values as data attributes on the button. You can then
access them from JavaScript.
JavaScript:
function displayListCart(listCart) {
var myList = document.getElementById("myList");
for (i = 0; i < listCart.length; i++) {
myList.innerHTML = myList.innerHTML + listCart[i].Name + " : " + listCart[i].Price;
}
};
function addToList(name, price) {
var itemOrder = {};
//itemOrder with data
itemOrder.Name = name;
//debugging -- check to make sure this returns what you expect
console.log(itemOrder.Name);
itemOrder.Price = price;
//debugging -- check to make sure this returns what you expect
console.log(itemOrder.Price);
//Add newly created product to our shopping cart
//declare listCart before you use it
var listCart = [];
listCart.push(itemOrder);
//pass listCart to the display function
displayListCart(listCart);
}
function getValues() {
addToList(myBtn.getAttribute('data-name'), myBtn.getAttribute('data-price'));
}
var myBtn = document.getElementById("btn");
myBtn.addEventListener("click", getValues, false);
Notes:
You need to declare listCart before you add objects to it.
I suspect you intended to pass listCart to the display function so that you can access the objects within it for display.
You were missing the logic that adds the values to the div. You need to iterate over the array and access the object properties.
First of all, if you open the Dev Tools, you will see an error - Uncaught ReferenceError: listCart is not defined. So the first thing you need to do is create listCart array, like this : var listCart = [];
Then you should modify your displayListCart function, to display a new div for every item in listCart, like this:
function displayListCart() {
var myList = document.getElementById("myList"),
myListContent = "";
listCart.forEach(function(cart) {
myListContent += "<div>" + cart.Name + ": " + cart.Price + "<div>";
});
myList.innerHTML = myListContent;
};
The code example

Simple ToDo-List doesn't work

My ToDo List dont wanna work the way i want. I've just been working with JavaScript for 2 weeks sthis is very new to me, therefor the code maybe doesnt look that nice.
The result comes out wrong. If I type in "buy food" the first line gonna show just that, but the next time I wanna add "walk the dog", then it displays
buy food
buy food
walk the dog
I hope you understand my problem. It also ends the unordered list tag after the first click and adds the rest of the things in another.
Here's the JavaScript:
var taskList = [];
var text = "<ul>"
function addToList() {
var task = document.getElementById("toDoTask").value;
taskList.push(task);
for(i = 0; i < taskList.length; i++){
text += "<li>" + taskList[i] + "</li>" ;
}
text += "</ul>";
document.getElementById("todoList").innerHTML = text;
}
The issue is you're closing the ul tag after adding each item. Instead of concatenating raw HTML, consider using element objects and appending, and using a text node object to handle the user input - this removes the possibility of a DOM Based XSS vulnerability.
window.onload = function() {
var taskList = [];
var container = document.getElementById("todoList");
document.getElementById("add").onclick = addToList;
function addToList() {
var task = document.getElementById("toDoTask").value;
taskList.push(task);
var ul = document.createElement('ul');
var li;
for (i = 0; i < taskList.length; i++) {
li = document.createElement('li');
li.appendChild(document.createTextNode(taskList[i]))
ul.appendChild(li);
}
container.innerHTML = '';
container.appendChild(ul);
}
};
Task:
<input id="toDoTask" /> <input type="button" id="add" value="Add" />
<div id="todoList">
</div>
You should not use the innerHtml. This replace all the text of your content. You should just add the li to your ul.
You can do that by using the append function by jquery Append
your <ul> must contain an id like this <ul id="toDoList">
then you make $("#toDoList").append("yourTask");
yourTask must contains the li.
With this, you don't need to iterate on all your element list
Not sure, but you seem to keep adding to text the second time, so text will be something like <ul><li>buy food</li></ul><li>buy food</li><li>walk the dog</li></ul>, which is invalid HTML by the way, but gets outputted anyway...
On each call of function addToList() you should reset the variable text.
For example:
function addToList() {
var task = document.getElementById("toDoTask").value;
taskList.push(task);
text="";
for(i = 0; i < taskList.length; i++){
text += "<li>" + taskList[i] + "</li>" ;
}
text += "</ul>";
document.getElementById("todoList").innerHTML = text;
}
The whole list of items in array will appends to variable text on each call.

Show Multiplication Tables with a button

I want to make a page with JavaScript that has a button saying "Multiplication Tables." When I click the button, the multiplication table of 5 will show up in the "p" tag with the id "tables." I want to use a for loop to calculate the tables. Nothing is happening when I click the button.
HTML:
<body>
<button type="button" id="multiplication" onclick="table()">Multiplication Tables</button>
<br/>
<p id="tables"></p>
</body>
</html>
JavaScript:
function table()
{
var button = document.getElementById('multiplication');
var showTables = '';
for (var i=1; i<12; i++) {
showTables += 5 + "*" + i +"="+5*i + '\n';
}
var p_tables = document.getElementById('tables').innerHTML = showTables;
}
table();
Check this snippet by clicking run snippet button below, I think it's working fine
function table()
{
var button = document.getElementById('multiplication');
var showTables = '';
for (var i=1; i<12; i++) {
showTables += 5 + "*" + i +"="+5*i + '\n';
}
var p_tables = document.getElementById('tables').innerHTML = showTables;
}
<html>
<body>
<button type="button" id="multiplication" onclick="table()">Multiplication Tables</button>
<br/>
<p id="tables"></p>
</body>
</html>
Your are missing html tag before body and there might be some problem with your javascript inclusion, Also don't run table() function after declaring it.
Place the script either in head tag or before closing the body. Remove table() function calling after declaring it.

Need help calling a function with parameters in JavaScript

I am working on a college project which is basically an elaborate news summarizer. I need to dynamically generate a list of article headings upon clicking a topic.
I have been able to do that and assign the list Ids and Values dynamically using the for loop.
Each list is clickable and calls a parameterized function, with parameter as that lists value.
I am unsure how to define the function and syntax to make this a possibility.
I need to do this so that each heading when clicked can use AJAX to interact with a servlet and generate an article corresponding to the heading based on their values.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
function change() {
var i = 0;
var set;
document.getElementById('content').innerHTML = '';
for (i = 1; i < 6; i++) {
var div = document.getElementById('content');
div.innerHTML = div.innerHTML + '<a href="#" onClick="rem()">'
+ '<h2 id="theading'+i+'" value="'+i+'">HEADING ' + i
+ ' WILL GO HERE</h2></a><br>';
}
}
function rem(value) {
document.getElementById('content').innerHTML = value
+ '<h1>THE NEWS WILL GO HERE</h1>';
}
</script>
</head>
<style type="text/css">
* {
list-style: none;
}
a {
text-decoration: none;
color: inherit;
}
a:hover {
color: orange;
}
</style>
<body>
<h3>TOPIC</h3>
<div id="content"></div>
</body>
</html>
How do I write the code so that rem() function can be called with its parameter as the value of its corresponding list.
I would completely rewrite your first function:
function change() {
var i = 0;
var set;
var div = document.getElementById('content');
div.innerHTML = '';
for (i = 1; i < 6; i++) {
var a = document.createElement('a');
a.href = "#";
a.onclick = rem.bind(null, i); // Here is the magical part
a.innerHTML = '<h2 id="theading'+i+'">HEADING ' + i
+ ' WILL GO HERE</h2>';
div.appendChild(a);
div.appendChild(document.createElement('br'));
}
}
Embrace the power of this.
onClick="rem(this)"
This will pass a reference to the clicked element. From there you can then traverse the DOM, using parents and children, to locate other elements, without having to deal with messy IDs.
You need to pass that value to method rem().
I am not absolute sure which value you wan't to pass for it but changing:
onclick="rem()"
to:
onclick="rem(' + i + ')"
will call method rem with an value of i when the link is clicked.
After that you can and should discard value="'+i+' from your h2 tag. It is not valid HTML.
Cheers.

Categories