I am using Chrome 30.0.1599.101 and have issue with name element: it has no properties.
<html>
<body>
<form>
<input name="name" id="name" type="text">*<br>
<input name="pass" id="pass" type="text">*<br>
</form>
<script>
var name = document.getElementById("name");
var pass = document.getElementById("pass");
console.log(name); // no properties
console.log(pass); // everything ok
</script>
</body>
</html>
Why has name element has no properties? It's not only the console issue - the properties are not accessible in the code. However, everything works fine in Firefox browser. Even in the fiddle (by Gurpreet Singh) with the very same code in the same browser everything works. I tried <!DOCTYPE html5> as Uooo suggests, tried to reset the browser, but still no luck on localhost.
Here is a screenshot:
If I change the name name to something else, the properties are visible.
name is already a global property (a property of window), and not only that, it is kinda typed (String).
var name = ... is essentially the same as as saying window.name = .... Use another variable name that is actually not taken yet and you should be fine.
Missing <head> and <title>, maybe that helps, it's invalid HTML without them.
jsfiddle does automatically insert those tags, which could explain why it works there but not locally.
Don't get confused by Green arrow answer,
you don't close an input tag, but not the br and vice versa. All single-tags in XHTML need to be closed to be valid, but in HTML4 and HTML5 you don't close any single-tag at all.
I would suggest following changed version which works as intended for me in
navigator.userAgent
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1678.0 Safari/537.36"
Code
<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script>
document.addEventListener('readystatechange', function(event) {
if (event.target.readyState !== "complete") {
return;
}
var name = document.getElementById("name");
var pass = document.getElementById("pass");
console.log(name);
console.log(pass);
}, false);
</script>
</head><body>
<form>
<input name="name" id="name" type="text">*<br>
<input name="pass" id="pass" type="text">*<br>
</form>
</body></html>
Explanation
script elements should be in the head element of a HTML document.
script code dealing with the DOM needs to run after the document is fully loaded.
Implicitly Fixed Issues
script code should not run in global scope where var name and pass may clash with existing variables. It now runs in the scope of the anonymous event listener function.
Remaining Problems
Use type="password" for password fields.
Use the value attribute to default input type values.
Better use div elements to layout input elements vertically instead of br elements.
I don't know if that cause the error but you should at least close your input
<html>
<body>
<form>
<input name="name" id="name" type="text"/>*<br>
<input name="pass" id="pass" type="text"/>*<br>
</form>
</body>
</html>
The fiddle works for me too...
Do you have any warnings &/or errors in your chrome console ?
You should also used your script in that function :
<script>
$(function() { //shortcut for document ready
//Get your elements here otherwise you can't be sure that dom is loaded.
});
</script>
if you don't use jquery then it's quite a mission to detect when dom is loaded if you want a Xbrowser solution, a lot of topic are talking about that.
Related
There is an html as follows:
<input id="currency_factor" type="text" style="display:none;" value="20"/>
And there is a jquery function:
$(document).ready(function(){
var currency_factor = $('#currency_factor').val()
alert(currency_factor);
}
Upon refresh the html line shows on the browser as:
<input id="currency_factor" type="text" style="display:none;" value="0"/>
But jquery returns 20.
Why is this happening?
Try adding this to the header of your html file to disable caching:
<meta http-equiv="Cache-Control" content="no-store" />
There are actually a number of cache control tags that may or may not be needed, depending on the browsers being used. Here's another posting on StackOverflow that lists some of them: Using <meta> tags to turn off caching in all browsers?
Try by first initializing it and then setting it
$(document).ready(function(){
var currency_factor = 0;
currency_factor = $('#currency_factor').val()
alert(currency_factor);
}
Do you perhaps have more than one element with an id of currency_factor. The first one's value will probably be returned.
Another possibility is that the value is changed after the $(document).ready() function has executed. Try running $('#currency_factor').val() in the browser console after load. If it returns 0 then it was changed after the page load.
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.
This script produces the expected results in Safari, but not Firefox. (These are the only two browsers I've tested it with.)
Here is the relevant HTML:
<form name="inputForm">
Weight:<input type="number" name="weight"> (lbs) <br>
Height:<input type="number" name="height"> (inches) <br>
<hr>
<input type="button" name="process" value="Calculate" onclick="calcBMI(weight.value, height.value)">
<hr>
BMI: <input type="text" readonly name="bmiResult">
</form>
And here is the entire Javascript, which is placed in the <head>...</head> tags of the HTML:
<script>
var BMIMULTI = 703;
function calcBMI(weight, height)
{
var bmi = (weight * BMIMULTI) / (height * height);
document.inputForm.bmiResult.value = bmi;
}
</script>
The consoles in both browsers show no errors. I have no external files I am linking to for either CSS or JS.
From my own debugging, I've discovered the problem lies with the height.value in the onclick="calcBMI(...)". The value for height.value is being passed in to the calcBMI function as null, whereas the weight.value is passed in appropriately.
In Safari, both values are passed into the calcBMI function successfully.
Why does this happen? And, why does it occur in Firefox and not Safari?
I'm new to javascript, thanks for your help.
The input element (which is the current scope within the event handler) also has a height property in some browsers, which will prevent you from accessing the field by that name from the outer scope.
Get the fields as members of the form instead of using the global scope:
calcBMI(this.form.weight.value, this.form.height.value)
Try to prevent using common word like height as your variable.
I have experienced similar problem before. I used "remove" as function name which works fine in the past but failed after firefox update.
I used this javascript code in my page & then checked against w3c validator. I got 2 errors which are:
there is no attribute "onKeyDown"
there is no attribute "onKeyUp"
I won't change my html declaration type to transitional. So I need modification in script.
Script HTML
<textarea id="message" cols="20" rows="5" name="message" onKeyDown="textCounter('message','messagecount',100);" onKeyUp="textCounter('message','messagecount',100);"></textarea>
<span id="charsleft"></span>
Script Javascript:
<script>
function textCounter(textarea, countdown, maxlimit) {
var textareaid = document.getElementById(textarea);
if (textareaid.value.length > maxlimit)
textareaid.value = textareaid.value.substring(0, maxlimit);
else
document.getElementById('charsleft').innerHTML = '('+(maxlimit-textareaid.value.length)+' characters available)';
}
</script>
<script type="text/javascript">
textCounter('message','messagecount',100);
</script>
Since I know nothing about javascript, I kindly ask you: what should be the modification so my page will be XHTML 1 strict validated? Or do I have to look for another script that is XHTML 1.0 Strict validated and does the same stuff?
Note: For the time being script works in this way: when you write in textarea, the part between two spans in <span id="charsleft"></span> appears and writes the number of remaining characters in real time. The way of showing style is not important for me. For example, first value (limit for number of characters) can be always visible. Only point is validation of W3C.Thanks, BR
The w3c validator includes a "How to fix" hint when it gives errors like that.
In your case, it says:
How to fix: check the spelling and case of the element and attribute, (Remember XHTML is all lower-case)...
That is, change the attribute names to be all lower case:
<textarea id="message" cols="20" rows="5" name="message" onkeydown="textCounter('message','messagecount',100);" onkeyup="textCounter('message','messagecount',100);"></textarea>
<span id="charsleft"></span>
It would be better to remove the inline event attributes and add event handlers from the JS in your script block, but I'm feeling lazy so I'm declaring that out of scope. (Google "unobtrusive javascript" for some hints about that.)
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'