Need help calling a function with parameters in JavaScript - 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.

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

Making table with objects in array?

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>

adding results of XML request to a page

I am trying to get a feel for adding content to a page with XMLHTTPRequest. I would like to add the results to existing page content say in a second column, but I am not having any luck. I would appreciate a shove in the right direction. Thanks for any help.
<!DOCTYPE html>
<html>
<head>
<style>
#button{
float: left;
}
#team{
float: left;
}
</style>
<title>XMLHTTPRequest</title>
<script src="jquery-1.10.2.js"></script>
<script>
$(document).ready(function(){
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && xhr.status == 200) {
xmlDoc = xhr.responseXML;
var team = xmlDoc.getElementsByTagName("teammember");
var html = "";
for (i = 0; i < team.length; i++){
html +=
xmlDoc.getElementsByTagName("name")[i].childNodes[0].nodeValue + "<br>" +
xmlDoc.getElementsByTagName("title")[i].childNodes[0].nodeValue + "<br>" +
xmlDoc.getElementsByTagName("bio")[i].childNodes[0].nodeValue + "<br><br>";
}
//this is the code I would like help with
var team = document.getElementById("team");
team.appendChild(document.createTextNode("html"));
}
}
xhr.open("GET", "team.xml", true);
});
</script>
</head>
<body>
<div id="button">
<button onclick="xhr.send()">Click Me!</button>
</div>
<div id="team">
</div>
</body>
</html>
I wrote a script fairly similar to yours that does nearly exactly what you are on about. Below is the some normal JavaScript I used to put it all on the page, I have changed some of the variable names so it compares nicely with your code.
for (i=0; i<team.length; i++)
{
//Create text nodes for each element as that's what appendChild() needs
var nameText = document.createTextNode(xmlDoc.getElementsByTagName("name")[i].childNodes[0].nodeValue);
var titleText = document.createTextNode(xmlDoc.getElementsByTagName("title")[i].childNodes[0].nodeValue);
var bioText = document.createTextNode(xmlDoc.getElementsByTagName("bio")[i].childNodes[0].nodeValue);
//This div will contain one team member's info
var memberDiv = document.createElement('div');
//Add text to the div created
memberDiv.appendChild(nameText);
//Line break
memberDiv.appendChild(document.createElement('br'));
memberDiv.appendChild(titleText);
memberDiv.appendChild(document.createElement('br'));
memberDiv.appendChild(bioText);
//Add the div we've just created to the document.
document.getElementById('team').appendChild(memberDiv);
}
This may need some more adapting to suit your needs but you get the general idea. This is just one way of doing it, there's probably loads of other ways including with jQuery that may be a bit neater actually.
You can use memberDiv.setAttribute('class', className) to set the class of each div to whatever you want
Below is a visual representation of this code to make it easier to understand, click for full scale (500*1750):

JavaScript onclick functions unbound due to innerHTML usage

I have a function in javascript that I intend to use to create/add a link to a 'subLink' div, and add an onclick event to this link that loads associated 'content' to a contentDiv:
function addSubLink(text, name, content) {
// append programLink span to subLinks:
document.getElementById("subLinks").innerHTML += "<span class=\"programLink\" id=\"" + name + "\">" + text + "</span>";
// load program content onclick:
document.getElementById(name).onclick = function () {
// set value of programContent to content's value
document.getElementById("programContent").innerHTML = content;
}
}
This function would be called, for example, by loadAboutPage() to populate the subLink div
var whatContent = "<p>A website!</p>";
var whyContent = "<p>Recreation!</p>";
var howContent = "<p>Kludges.</p>";
addSubLink("WHAT", "whatLink", whatContent);
addSubLink("WHY", "whyLink", whyContent);
addSubLink("HOW", "howLink", howContent);
The problem is that only the last subLink has an onclick event attached to it (content is loaded and css class changed). That is, it creates WHAT, WHY, and HOW links, but only appends the onclick function to the last called: HOW, in this case.
I'm very rusty when it comes to JavaScript, so I have no idea if it's a result of my lack of knowledge about anonymous functions, or using the local 'name' variable incorrectly, or anything else completely different. I've searched for awhile, but it seems I'm too ignorant to even figure out what a similar problem would be!
Anyway, I greatly appreciate your help! Thanks in advance!
EDIT:
Here's a complete HTML example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Stack Overflow Example</title>
<script type="text/javascript">
function addSubLink(text, name, content) {
document.getElementById("subLinks").innerHTML += "<span class=\"programLink\" id=\"" + name + "\">" + text + "</span>";
document.getElementById(name).onclick = function () {
document.getElementById("program").innerHTML = content;
}
}
window.onload = function() {
var whatContent = "<p>A website!</p>";
var whyContent = "<p>Recreation!</p>";
var howContent = "<p>Kludges.</p>";
addSubLink("WHAT", "whatLink", whatContent);
addSubLink("WHY", "whyLink", whyContent);
addSubLink("HOW", "howLink", howContent);
}
</script>
</head>
<body>
<div id="container">
<div id="programWindow">
<div id="subLinks"> </div>
<div id="program"> </div>
</div>
</div>
</body>
</html>
The issue is due to:
....innerHTML += "...";
By setting innerHTML, all existing child elements are first removed, then the markup is parsed to create new elements. So, while the original "WHAT" and "WHY" spans did have onclick bindings, they've being replaced by similar elements that don't.
To append a new element and keep state, you'll want to use DOM methods like createElement(), appendChild(), and createTextNode() (or set textContent/innerText):
function addSubLink(text, name, content) {
var span = document.createElement('span');
span.className = 'programLink';
span.id = name;
span.appendChild(document.createTextNode(text));
// append programLink span to subLinks:
document.getElementById('subLinks').appendChild(span);
// load program content onclick:
span.onclick = function () {
// set value of programContent to content's value
document.getElementById("programContent").innerHTML = content;
};
}
Example: http://jsfiddle.net/bG7Dt/

Categories