Using an array inside of a function to store names - javascript

I am trying to practice javascript and I read a small challenge on a website about making a small system where users can follow and unfollow one another. I am still new to javascript and programming in general so please forgive my ignorance. Below is what i came up with. I am trying to make this off the top of my head because this might be the best way to learn a language imo.
Basically in this small function, I created an empty array set in a function. I then set the function to the onClick handler in the tag. Is this a good way to store names or things in general? Am I on the right track to do this small task?
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id="searchbox" value = "names">
<button type="radio" onClick="listOfPeople();">
<script type="text/javascript">
"use strict";
function listOfPeople (){
var storedPeople = [];
listOfPeople();
};
</script>
</body>
</html>

Since you've declared the storedPeople array inside the listOfPeople function, that will limit the "scope" from where you can add or remove items from it to the listOfPeople function.
Something like this would not work with your setup currently, because the storedPeople array is is in a "closure" because it was declared inside a function.
<script type="text/javascript">
function listOfPeople (){
var storedPeople = [];
listOfPeople();
};
alert(storedPeople[0]);
</script>
This should show how to declare the array outside of the function so it has a "wider scope", meaning that it can be accessed by more than just inside of the listOfPeople function.
<!DOCTYPE html>
<html>
<body>
<input id="searchbox" value = "names">
<button type="radio" onClick="listOfPeople();">
<script type="text/javascript">
// declare the storedPeople array outside of the function
var storedPeople = [];
// modify the array in the function
function listOfPeople (){
storedPeople.push(document.getElementById("searchbox").value);
};
</script>
</body>
</html>

You're properly calling your button.
But there's one problem within your javascript function : inside of 'listOfPeople' you're calling 'listOfPeople'.
You shouldn't do this because it will never stop calling the same function again and again. And then stack overflow : Maximum call stack size exceeded.
Your function should look like :
function listOfPeople (){
var storedPeople = [];
};
Otherwise it is a good start!

you have not clearly mentioned what you need your given code to do.
like others mentioned, listofpeople() is recusrive but there's no condition to break it.
try to create your code in http://plnkr.co/ and explain what is it that you want as opposed to what is happening.

in case you want to do the search progressively as the user types you may use 'onchange' see the demo here http://www.w3schools.com/jsref/event_onchange.asp
as a modification to Zack's code it would be
<body>
<input id="searchbox" value = "names" onchange="listOfPeople();">
<button type="radio" onClick="listOfPeople();">

Related

Editing and Updating a HTML list with JavaScript

I'm trying to create a list which I can edit/update. I'll need to be able to store the list information in a variable of some sort and display the information on a HTML page.
My attempt is in the jsbin below.
JSBIN
https://jsbin.com/luxobineze/edit?html,js,console,output
So with that code, I'd like to:
Add names by filling in the form and clicking "Add Name"
Click [Edit] which will fill the form with the name that is to be edited
Click Update to update the global variable "names" (If I can do this, then I should be able to update the HTML's "List of Names" as well)
I'm not sure what to do in the updateName function since I'm not sure how to pass the relevant arguments into it in order to update the correct list item. Do I need to use more global variables to keep track of the list item that's being edited? Or is there a better, more standard way of coding this?
The code in the jsbin is here:
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
Name: <input type="text" id="name-input"><br>
<button id="add-name" class="button">Add Name</button>
<button id="update" class="button">Update</button>
<div id="list">List of Names</div>
</body>
</html>
JavaScript
// global variable storing the list of names
var names = [];
function addName() {
var name = document.getElementById("name-input").value;
var list = document.getElementById("list");
if(name) {
names.push("name");
var wrapper = document.createElement("div")
wrapper.setAttribute("id", name)
var div_name = document.createElement("div");
div_name.appendChild(document.createTextNode(name))
var div_edit = document.createElement("div")
div_edit.appendChild(document.createTextNode("[edit]"))
div_edit.addEventListener("click", editName)
wrapper.appendChild(div_name)
wrapper.appendChild(div_edit)
list.appendChild(wrapper)
}
}
function editName() {
// Fill the input box with the name that you want to edit
var name = this.parentElement.getAttribute("id")
document.getElementById("name-input").value = name;
}
function updateName() {
var new_name = document.getElementById("name-input").value
// How do I update the global variable "names"?
}
document.getElementById("add-name").addEventListener("click", addName)
document.getElementById("update").addEventListener("click", updateName)
Edit
I ended up using some global variables to keep track of which item was currently selected: https://jsbin.com/zupawesifu/1/edit?html,js,console,output
What it sounds like you're doing is building the most basic of applications, a CRUD app. (Create, Read, Update, Delete)
Storing your values in a local variable is not the most desirable way of doing this, unless of course that is your desired functionality.
You ask "is there a more standard way". A more common way would be to store your values in a database, or, in an even simpler scenario, you could store these values in a local .JSON file. This will allow you to use your application at any time, close the application, refresh, or any other number of things without losing your stored or edited values.
I won't code a full CRUD app for you here, but there are many tutorials and templates out there for your learning pleasure. Here is very basic one.
I hope this helps!
http://mrbool.com/creating-a-crud-form-with-html5-local-storage-and-json/26719

Changing input value with javascript - what went wrong?

I have a text with an input field. I want the field to start as blank, and when clicked upon, set the input's text to its correct value (saved in the "name" field, for instance).
If I do it this way, it works fine:
Buy <input type="text" name="eggs" onclick="this.value=this.name;"> tomorrow.
However, if I try to clean the DOM and move the function to a separate javascript file, it stops working:
HTML:
Buy <input type="text" name="eggs" onclick="showname(this);"> tomorrow.
JS:
function showname(el) {
el.value = el.name;
}
function showname(el){
el.value = el.name;
}
.closeform{
width: 70px;
}
.closeform input {
width: 70px;
}
.closeform button {
width: 70px;
}
Buy
<span class="closeform">
<input type="text" name="eggs" onclick="showname(this);">
</span>
tomorrow.
I'm very new to Javascript - what am I missing here?
You say in your question:
However, if I try to clean the DOM and move the function to a separate javascript file, it stops working
Let's say you have 2 actual files in the same folder:
myscript.js contents:
function showname(el) { el.value = el.name; }
index.html contents:
<!DOCTYPE html>
<html><head><title>Demo</title>
<script src="myscript.js"></script>
</head><body>
Buy <input type="text" name="eggs" onclick="showname(this);"> tomorrow.
</body></html>
OR
<!DOCTYPE html>
<html><head><title>Demo</title>
</head><body>
Buy <input type="text" name="eggs" onclick="showname(this);"> tomorrow.
<script src="myscript.js"></script>
</body></html>
That should work perfectly...
However, in the comments you say:
I tried it with Fiddle - maybe the problem is in Fiddle interface.
That is where your problem was....
There is no separate javascript-file in jsfiddle.
The three code-blocks (html, js, css) get merged into one file.
Right-click the result-window in jsfiddle and look at the generated file.
Then notice the options (top right corner) from jsfiddle: by default the code is wrapped in an onload-method (suiting to the library you selected or window.onload if you are not using a library).
You can however place the script in the head or body, thereby not wrapping your code inside a function's scope (which then closes over the containing identifiers).
See http://jsfiddle.net/wf55a5qb/ for a working example.
The reason your example stack-snippet worked here on StackOverflow is that it's snippet-editor does not wrap the javascript codeblock in a (onload-like) function (when it combines the three code-blocks).
Having said and explained this, I do encourage you to set your events (Using obj.addEventListener/obj.attachEvent or the direct elm.onevent) from the/a script once the elements (that your script manipulates, place script as last element of the html-body) or page (using window.onload/etc) has loaded.
I posted this to clear up what actually went wrong so you don't make false models in your head about how javascript works (like "an external script runs in it's own scope" which no-one claimed but might be an assumption you might make) whilst still learning it!
Everything in JavaScript has a scope. Where you are defining your function, it is not visible to the input so the input doesn't know that function even exists. You can use window to make the function visible to it:
<input type="text" name="eggs" onclick="window.showname(this);"/>
window.showname = function (el)
Fiddle
I don't recommend global functions though. So then what else?
You can use the onclick function in JavaScript. To find elements in JavaScript, you use selectors. I'm using getElementById() this will get an element by it's id. A list of selectors are here
<input id="my_input" type="text" name="eggs"/>
Then in JavaScript:
document.getElementById('my_input').onclick = function () {
//Use this to refer to the element
this.value = this.name;
};
Fiddle
When doing this. Make sure all your code is wrapped in a window.onload. This will make sure the code is run at the right time:
window.onload = function () {
//Your code
};
JSFiddle automatically puts your code in this.

html assigning value to input text using javascript does not work

I am new to programming and I have a small problem
I have a form named "fr" with an input text box named "in" and a variable "n" with the value of "my text"
this is my code what I have:
<html>
<head>
<script LANGUAGE="JavaScript">
var n = "my text";
document.fr.in.value = n;
</script>
</head>
<body>
<form name="fr">
<input name="in" size="3">
</form>
</body>
</html>
but somehow input "in" does not show the text "my text"
I have been browsing the internet but I couldn't find any solution which works..
everything what I try does not work.
I think I am doing something very simple wrong.
please help me.
document.fr does not exist yet at time of invocation; hence, everything following it doesn't exist either, so it throws a TypeError
TypeError: Cannot read property 'in' of undefined
To fix this, move your code to be invoked after the nodes exist, using your favourite method
window.addEventListener('load', function () {
var n = "my text";
document.fr.in.value = n;
});
I'll further note that;
The preferred way to look up an Element is to give it an id attribute and use document.getElementById. An id must be unique.
Using the language attribute of <script> is depreciated, if you want to specify the language, use the type attribute type="text/javascript" or type="application/javascript"
Opening the Console when a script is not working as expected will often show you the cause immediately. This is usually done with F12.
You should init the script after the form is defined, as explained by Paul S. in his answer. So you may do,
<html>
<head>
</head>
<body>
<form name="fr">
<input name="in" size="3">
</form>
<script type="text/javascript">
var n = "my text";
document.forms.fr.in.value = n;
</script>
</body>
</html>
This would run the script after the form is defined. Or put this code in some function, and instantiate the function after the form is defined(i.e. loaded).
As Paul pointed out you should only try to get a hold of page elements when you are certain that the element you are interested has already been loaded. So in this case you can set the value of the input field by running your code when the page has fully loaded and by getting a reference to the input like this:
window.addEventListener("load", function () {
var n = "my text";
var myInput = document.getElementsByName("in");
myInput[0].value = n;
});
Note, because getElementsByName() returns an array, you will have to use [0], to get the first element.

JavaScript clear text box input not functioning properly

I know that this is an embarassingly easy question, but I can't figure out the problem, and that's why I'm asking the question, so please don't reiterate this point.
Anyway, I'm just working on something here, and when I tested my page to see how things were going, I realized that my calculate() method isn't clearing text input like I want it to.
Here is the markup and the script:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Quadratic Root Finder</title>
<script>
function calculate(){
var valuea = document.form1.variablea.value;
var valueb = document.form1.variableb.value;
var valuec = document.form1.variablec.value;
document.form1.variablea.value = "";
document.form1.variableb.value = "";
document.form1.variablec.value = "";
}
</script>
</head>
<body>
<form name="form1">
a:<input name="variablea" value="" type="text">
<br/>
b:<input name="variableb" value="" type="text">
<br/>
c:<input name="variablec" value="" type="text">
<br/>
<input name="calculate" value="Calculate!" type="button" onClick="calculate()">
</form>
</body>
</html>
Please tell me if you see anything.
You might want to try using another name. I tried to call the "calculate" function but it keeps on giving me an error saying "calculate" is not a function. But when I call the function "calculateQuad" and change the onClick event to call "calculateQuad" it works.
Not very sure, but if you don't want to move to jQuery here's what you could try:
function calculate() {
var inputa = document.getElementById('inputa');
inputa.value = '';
}
Just test this, having an id "inputa" on one of the input boxes. I only know how to get elements by id, name or tag in raw Js. Of course, you could then extend your code to what you want using one of these methods to get your form elements.
Inside the onclick method is there a reference to the item you clicked. It is named the same as the name you put on the item, "calculate". This results in that "calculate" does not refer to the function, but the input tag.
To resolve this by either typing
onclick = "window.calculate()"
or rename the name of either the input-tag or the function.
change the name of the input button to something else:
<input name="calcul" value="Calculate!" type="button" onClick="calculate()">
and it works. Since the calculate function is residing directly under the global object, I have a weird feeling your name attribute is somehow overwriting it.
Just throwing this out there. I will take a deeper look at why this is happening though.

Can a JavaScript variable be used in plain HTML?

What I mean is, can a variable/array declared and initialized be used in HTML, outside the <script>-tags? Fx.
<script type="text/javascript">
var foo = array('placeholder1', 'placeholder2');
</script>
<body>
<p><!--access the variable here-->foo[0]</p>
</body>
How do you access the variable/array in this case? like this:
<p><script type="text/javascript">document.print(foo[0])</script></p>
??
Two ways to do this. This is the better one:
<script type="text/javascript">
// make sure to do this onLoad, for example jQuery's $()
var foo = array('placeholder1', 'placeholder2');
document.getElementById("fooHolder").innerHTML = foo.toString();
</script>
...
<p id="fooHolder"></p>
Or you could do it this way (which, as Marcel points out, doesn't work in XHTML and really shouldn't be used anyway):
<p><script type="text/javascript">document.write(foo)</script></p>
You can do something like this:
<script>
var str = 'hello there';
document.getElementById('para').innerHTML = str;
</script>
where an element has the specified id:
<p id="para"></p>
you simply cannot access javascript variable outside of the script tag, it is because,
Html does not recognise any variable it just renders the supported HTML elements
variables are used to store the temporary variables, that is for dynamic data, if you want something more dynamic then you can use PHP for that.
Unnecessarily verbose, but using standard DOM methods.
<script>
window.onload = function(){
// you do not need to initialize like this, but I like to
var bar1 = new String('placeholder1');
var bar2 = new String('placeholder2');
var foo = new Array();
// populate the Array with our Strings
foo.push(bar1);
foo.push(bar2);
// create an array containing all the p tags on the page
// (which is this case is only one, would be better to assign an id)
pArray = document.getElementsByTagName('p');
// create a text node in the document, this is the proper DOM method
bar1TextNode = document.createTextNode(foo[0].toString());
// append our new text node to the element in question
pArray[0].appendChild(bar1TextNode);
};
</script>
<body>
<p></p>
</body>
That's the only direct way you'll access it elsewhere in your page. By opening another script tag and printing it.
You can also use methods such as innerHTML to put the value somewhere.
I don't think you can access the javascript from html but you can set the innerhtml of a dom object through javascript so you may want to go the other way around. First google search I found so I cant promise its good but it has a quick sample.
http://www.tizag.com/javascriptT/javascript-innerHTML.php
You can even you AngularJS expression.
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.framework= "AngularJS";
});
</script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>I want to use variables directly in HTML using: {{ framework }}</p>
</div>
</body>
</html>
The above code will print out "I want to use variables directly in HTML using: AngularJS".You can use braces to write AngularJS expression. For example: {{ expression }}.

Categories

Resources