I'm trying to figure out why my javascript function isn't storing my JS variable.
Here's the issue. I trigger my storeMacAddress function with an onclick event, and the alert shows that the 'userMac' variable gets the form value properly. I need to be able to use this value later on, so I need the value stored in a variable that my other functions can user.
However, when I call my testVariable function, the console says that the 'usermac' variable is not defined.
Here's the javascript:
function storeMacAddress()
{
var userMac = document.getElementById("MacAddress").value
alert("testing: " + userMac);
return userMac;
}
function testVariable(MacAddress)
{
alert(MacAddress);
}
Here's the html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src='./index.js'>
</script>
</head>
<body>
<h1></h1>
<p></p>
<div>
<form id="userRequest">
Mac Address: <input type="text" id="MacAddress"><br>
<input type="submit"
onclick="storeMacAddress();"
value="Save Mac Address">
</form>
</div>
<button onclick="
testVariable(userMac);
">Test</button>
</body>
</html>
Since you are defining the variable inside the function, it is not visible outside the function or even to other functions, hence we can define it outside where it will be accessible to all the functions, you can just assign values inside the function or access it inside the function!
Note: I have changed type attribute of input to text, so that the
variable assignment is visible in the snippet!
var userMac;
function storeMacAddress() {
userMac = document.getElementById("MacAddress").value
if (userMac)
alert("testing: " + userMac);
return userMac;
}
function testVariable(MacAddress) {
if (MacAddress)
alert(MacAddress);
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src='./index.js'>
</script>
</head>
<body>
<h1></h1>
<p></p>
<div>
<form id="userRequest">
Mac Address: <input type="text" id="MacAddress"><br>
<input type="button" onclick="storeMacAddress();" value="Save Mac Address">
</form>
</div>
<button onclick="
testVariable(userMac);
">Test</button>
</body>
</html>
You are creating the variable within the scope of the function, and not within a closure. Learn about closure.
You are wiring the function inline, which means that your return is completely useless. Look up the concept of “unobtrusive JavaScript”. Keep your JS and HTML separate, if you don't use a view-binding layer, like JSX, and even if you did, keep your services and your view logic separate.
You are using a submit, inside of a form. Even if this did what you wanted, the page would immediately be reloaded, and you would lose everything. Look up form actions.
To submit to the server, your form field should have a name.
Related
In the following HTML/Javascript snippet, I'm missing the function's brackets in the onclick statement (it should read: onclick="showMessage()").
How could I get the missing brackets highlighted
(a) in Notepad before I display the page.
(b) in my Browser JS console after I display the page?
If this is not possible besides inspection, is there another way I could identify this issue more easily?
<html>
<head>
<script>
function showMessage() {
document.getElementById("messageArea").innerHTML = "Hello World";
}
</script>
</head>
<body>
<input type="button" value="Show message" onclick="showMessage">
<div id="messageArea">---</div>
</body>
</html>
The problem is onclick takes any kind of javascript expression, function execution being one of them. For example:
<script>
var a = 10
</script>
<!--All are valid and don't throw any errors -->
<button onclick="a">Nothing happens</button>
<button onclick="a++">Increment</button>
<button onclick="alert(a)">Check value</button>
<button onclick="undefined">Surely Not?</button>
Executing functions like showMessage() is one of it's primary use. And technically it's not an error to have a showMessage without the () inside the onclick. showMesage is just function definition, If you were to type showMessage and press enter in your browser's console, it will simply return the function definition and won't throw any error. So IDEs don't underline it as an error because it's not an error.
I don't know of any tool that will look at html attributes for possible errors like this.
However, if you move all of your javascript code to a separate file, you can use a tool like eslint to check for common errors.
So in this case, instead of using the onclick attribute in your HTML, you'd use javascript to select the element and add an event listener.
I want to create a website which can tell the circumference of a circle when the user inputs the radius. I've done the code, but its not working. Can you tell me why?
<html>
<head>
</head>
<body>
<form id="ty">
Give radius: <input type="number" input id="radius">
</form>
<p id="sum"> htht </p>
<button type="button" onclick="my()"> Click on me</button>
<script>
Function my() {
var r= document.getElementById("radius");
var a= r*2;
document.getElementById("sum").innerHTML=a;
}
</script>
</body>
</html>
I am getting an error "NaN" when I click on the button
Working HTML demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Language" content="en">
<meta charset="UTF-8">
<title>Radius to Circumference</title>
</head>
<body>
<form name="ty">
<ol>
<li>Give radius: <input type="number" name="radius"></input></li>
<li><input type="button" onClick="my();" value="convert"></input></li>
<li>Get circumference: <input type="number" name="sum"></input></li>
</ol>
</form>
<script LANGUAGE="Javascript">
function my() {
var r = document.ty.radius.value*1;
var a = r*2;
document.ty.sum.value = a;
}
</script>
</body>
</html>
when writing HTML, you should be certain to use proper semantics.
Specify a doctype, character set and language!
avoid using buttons that say things like "Click on me!" This is
redundant because the user has to read what they're going to do
before they do it. Instead, write what the button will do
on the button itself (in this case, "Convert" is what I used).
you did not include a title in your head.
and are two different elements with different
purposes. In this case, you want .
"function" should not be capitalized.
your r variable did not contain the number the user put in, but
rather, contained all the properties of the input element. You never
specified you wanted the number it contained, so instead, the
variable r contained all the information it could obtain about the
"radius" element including it's colour, it's size, and other useless
things you don't need. You are looking for it's value, hence why I
added .value on the end of that line.
I also added *1 to the end of r's line, so that if the user by
any chance did not enter a valid number, Javascript will correct that
issue (multiplying by one gives the same result but parsed into a number).
you were using the p element for the sum, but that wouldn't be a
paragraph now, would it?
I used an ordered list to add 1, 2, and 3 to the beginning of each
step.
I think you mean:
var r = document.getElementById("radius").value;
getElementByID returns the element, not its value. element*2 = NaN.
You want.
var r = document.getElementById("radius").value;
Also, you might want to parse the integer just in case:
var r = parseInt(document.getElementById("radius").value);
Very simple, from HERE you can find you need to change:
var r= document.getElementById("radius");
to
var r= document.getElementById("radius").value;
You have written whith uppercase F the function, note that the
javascript is case sensitive.
the value of the input element can get using the .value property.
in the input form element does not need twice using the input
keyword, only once on begin.
Here is a nicer way to write that, with some minor improvements.
it's preferred to write the javascript in the head.
by defining the various elements onload later you have faster&easier access to them.
also inline javascript is not suggested, don't write js inside html attributes.
Then talking about your errors:
function is not Function
document.getElementById('radius') should be document.getElementById('radius').value
<html>
<head>
<script>
var radiusBox,sumBox,button;
function my(){
sumBox.innerHTML=radiusBox.value*2
// the use of textContent is more appropiate but works only on newer browsers
}
window.onload=function(){
radiusBox=document.getElementById('radius');
sumBox=document.getElementById('sum');
button=document.getElementById('button');
button.onclick=my
}
</script>
</head>
<body>
<form id="ty">
Give radius:<input type="number" id="radius">
</form>
<p id="sum">Enter a number</p>
<button id="button">Click on me</button>
</body>
</html>
writing it this way it is compatible with every browser that supports javascript, a newer proper way would be using addEventListener to add the load and the click handler thus also allowing you to add multiple event handlers, but old ie's wouldn'ty work.also textContent could have prblems...
DEMO
http://jsfiddle.net/frma0zup/
if you have any questions just ask.
i'm trying to send a variable through to a function when clicking an image, but can't get any of it to work. not sure where I am going wrong.?
jsfiddle http://jsfiddle.net/cibravo/rNGMR/
HTML
<input type="submit" value="send" onclick="alert('works')" />
<br/><br/>
<img onclick="alert('works')" src="http://firmakurser.studieskolen.dk/images/web/Facebook-logo-small.png" />
<br/><br/>
<!-- this doesn't work -->
<input type="button" value="send" onclick="myFunction()" />
<br/><br/>
<!-- this doesn't work -->
<img onclick="showhide('works')" src="http://firmakurser.studieskolen.dk/images/web/Facebook-logo-small.png" />
JS
function myFunction(){
alert("works");
}
function showhide(field){
alert(field);
}
Both of your examples that you say don't work will work provided the functions they call are globals, not contained within any scoping function.
The reason it's not working in your fiddle is that jsFiddle's (surprising) default is to wrap your JavaScript code in a window load event handler, like this:
window.onload = function() {
// your code here
};
...so your functions aren't globals. (I say it's surprising because waiting until the window load event runs, which is very late in the page load process, is not best practice.)
Here's an updated fiddle: http://jsfiddle.net/rNGMR/4/ As Juhana points out, you change tehs second drop-down box on the upper left to one of the "no wrap" options (I went with "no wrap - body").
For clarity, here's a complete all-in-one example: Live Copy | Live Source
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Global Functions</title>
</head>
<body>
<input type="submit" value="send" onclick="alert('works')" />
<br/><br/>
<img onclick="alert('works')" src="http://firmakurser.studieskolen.dk/images/web/Facebook-logo-small.png" />
<br/><br/>
<!-- this doesn't work -->
<input type="button" value="send" onclick="myFunction()" />
<br/><br/>
<!-- this doesn't work -->
<img onclick="showhide('works')" src="http://firmakurser.studieskolen.dk/images/web/Facebook-logo-small.png" />
<script>
// Note that these are globals
function myFunction(){
alert("works");
}
function showhide(field){
alert(field);
}
</script>
</body>
</html>
More or less an alternity to your current approach
(which was solved while I wrote this.)
Please try avoid using the 'onclick' event when you work on bigger projects. It's usually better to keep HTML, CSS und JavaScript modularly separated.
When I encounter problems like this I usually use anonymous functions, who then call the
function with the right parameters.
This technique also solves the problem that everything needs to be global -- which is discouraged too.
It suited me well trough the last 3 years and around 15k lines of JavaScript code.
Here is an example:
http://jsfiddle.net/8jSaT/1/
<!-- HTML -->
<img id="btnSomething" src="http://firmakurser.studieskolen.dk/...">
// (plain) Javascript
var btn = document.getElementById('btnSomething');
// this is where the anonymous function comes in:
// Its only purpose is to redirect the onClick-Event
// and serve proper parameters
var btn.onclick = function() { showhide('works'); };
// Your code
////////////////
function myFunction(){
alert("works");
}
function showhide(field){
alert(field);
}
I'm trying to take user form input and display it back to the user, among other things (all of which require the input being stored as a JS variable).
I'm trying to spit it out in an alert, as a quick feedback loop, and all I keep getting is [object HTMLInputElement]. I've tried to use document.forms[0] and document.getElementById (like below) and neither work. Also, I'm using bootstrap typeahead, could that be complicating this issue?
What am I missing?
Here's the code:
<div class="hero-unit">
<h1> Title </h1>
<p> This form description </p>
<form class="well" name="formInput" action= "#">
<label>Input</label>
<input Id="txtvarInput" class="span3" style="margin: 0pt auto;" type="text" placeholder="AAA, BBB, CCC..." data-provide="typeahead" data-items="10" data-source="["AAA","BBB","CCC","DDD","EEE","FFF","GGG","HHH","III","JJJ","KKK","LLL"]"/>
</label>
<div class="form-actions" "span3">
<input name="submit" type="submit" class="btn" value="Select" onclick="alert('you chose ' + theInput.value)"/>
<script language="JavaScript" type="Text/JavaScript">
var theInput = document.getElementById('txtvarInput');
</script>
</div>
</form>
</div>
<div class="page-header">
<h1>Input:
<script language="JavaScript" type="Text/JavaScript">
document.write(theInput.value);
</script>
</h1>
Edit: PART II, now the code works for the alert, but I need to use it elsewhere (like I said) and the variable isn't available in other sections of the html. Above, I'm just trying to get it to display that same value as a part of the html. It could be my JS, but this is pretty boilerplate stuff, so I think it's related to the location of the variable.
What do I need to do use it elsewhere? I've added the next div above to show what I'm trying.
--left an extra declaration of the variable in part II by accident, was one of the tests I was trying, removed now.
Right now, the object you're alerting is an HTML element, not a string. You can get its value using the value property:
alert('you chose ' + theInput.value)
(Note that you probably didn't mean:
var theInput = document.getElementById('txtvarInput').value;
As other answers suggest, because that would give you an empty string. It's only read once.)
You are trying to output the entire HTML-object that you have selected, not the value-property of it. Since alert() expect a string, JavaScript gives you the string representation of that object which is [object HTMLInputElement].
Try this instead:
var theInput = document.getElementById('txtvarInput').value;
var theInput = document.getElementById('txtvarInput');
should be
var theInput = document.getElementById('txtvarInput').value;
In the alert, use
theInput.value
You need to use the value property:
var theInput = document.getElementById('txtvarInput').value;
You forgot .value
Something like:
document.getElementById('txtvarInput').value
You are going to print the value of the input at the page load time. You will get an empty alert.
just do this!
<input name="submit" type="submit" class="btn" value="Select" onclick="alertVal()"/>
<script language="JavaScript" type="Text/JavaScript">
function alertVal(){
var theInput = document.getElementById('txtvarInput').value;
alert('you chose ' + theInput);
}
</script>
I wrote the following code:
<form name=f>
<input type=button value="Button1" onclick=b1click()>
<input type=button value="Buttone2" onclick=b2click()>
<script language=javascript>
function b1click()
{
f.action="Login.jsp";
f.submit();
}
function b2click()
{
f.action="Logout.jsp";
f.submit();
}
</script>
</form>
This works code properly in Internet Explorer but the action does not work in Mozilla Firefox 3.6.2. How to solve this problem? Please any one help me.
I know this will sound snide, but the truth of the matter is: it's not 1995 anymore.
That code would have worked great a decade ago, but standards and specifications have changed significantly since then.
Lets start from the top:
<form name=f>
All html attribute values should be enclosed in quotes. For consistency sake, use double quotes: <form name="f"> is much better.
<input type="button" value="Button1" onclick="b1click()">
Avoid inline-script events. If the functionality ever changes, or you want to remove a function, you'll have to go through every page and adjust the function. A better way is to give the button an ID, and add the onclick event via scripts:
HTML:
<input type="button" value="Button1" id="button1">
JS:
document.getElementById('button1').onclick = b1click;
Now the script's turn:
<script language=javascript>
You should use the type attribute with a valid MIME type. Additionally, whenever possible, move your scripts to an external script file. When that's not possible, make sure to either XML encode your script, or encase it in CDATA tags:
<script type="text/javascript" src="path/to/script.js"></script>
OR
<script type="text/javascript">
/* <![CDATA[ */
... some code ...
/* ]]> */
</script>
Finally the real issue with your script.
The f property you're referencing is a member of the document, and not the window. I believe IE will put the reference on both, but it's just not safe to rely on either behavior.
Give the form an ID: <form id="f">, and get the element from the b[12]click functions
function b1click()
{
var f = document.getElementById('f');
f.action = 'Login.jsp';
f.submit();
}
First off, change that name="foo" to id="foo". Names are mostly used within the form itself.
Now, try to reference your form using document.formID, not just formID. formID is a variable, which is undefined, but document.formID is the actual form element:
function b1click()
{
document.f.action="Login.jsp";
document.f.submit();
}
function b2click()
{
document.f.action="Logout.jsp";
document.f.submit();
}
Give form an id and refer to it using:
var form = document.getElementById('formId');
You should quote the input attributes, or any attributes for that matter. And your script does not belong AFTER the form, e.g. in body, but rather in the HEAD element.
This works in IE, Firefox and Chrome.
<html>
<head>
<script language="javascript">
function b1click()
{
f.action="Login.jsp"; // better is document.f., but f. appears to work as well
f.submit();
}
function b2click()
{
f.action="Logout.jsp";
f.submit();
}
</script>
</head>
<body>
<form name="f">
<input type="button" value="Button1" onclick="b1click()">
<input type="button" value="Buttone2" onclick="b2click()">
</form>
</body>
</html>
There are a couple ways to reference your form.
If you define your form as <form name="Login" id="LoginFrom"></form>,
Method 1
If your form is the only one in the page, you can use:
document.forms[0].action = 'Login.jsp';
Method 2
If your form is not the only one form in the page, you can use the form name to reference the form, such as
document.Login.action = 'Login.asp';
Method 3
The form can also be referenced with DOM function getElementByID.
document.getElementByID('LoginForm').action = 'Login.asp'