Javascript code works in Safari, but not Firefox. Why? - javascript

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.

Related

Missing DOM element

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.

HTML objects not visible to JavaScript in Firefox 6

Is there any reason why I'm not able to see object values from JavaScript using Firefox, but IE and Chrome see them without problem?
For example:
<div>
<input type="text" id="clientID" />
<input type="submit" id="search" value="Submit" class="submitButton" />
</div>
JavaScript:
<script type="text/javascript">
$(document).ready(function () {
$("#searchDisputes").click(function () {
if(clientID.value.toString() != "") {
//do something
}
}
}
</script>
Firefox tells me that clientID does not exist, however IE and Chrome work just fine.
I am able to access it using jQuery $("#clientID"), but before changing a good bit of code around, I would like to understand why this doesn't work in Firefox, but works ok in other browsers.
You are assuming that giving an element an id will create a global variable with the same name as the id containing a reference to the element. There is no reason browsers should do this.

JavaScript doesn't work in Mozilla Firefox

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'

Radio Button won't work in internet explorer but works fine in firefox

I have HTML code like so:
function toggle_action(type) {
var tabs = document.getElementsByName("action_tab")
for(var i = 0 ; i < tabs.length; i++){
//alert(" i = " + i + " length=" + tabs.length );
if(tabs[i].id == type.value){
tabs[i].style.display='inline';
}else{
tabs[i].style.display='none';
}
};
}
a
<div id="action_types">
<input type="radio" checked name="action_type" value="EmailActionDescription" onclick="toggle_action(this);"/><label>Email</label>
<input type="radio" name="action_type" value="TicketActionDescription" onclick="toggle_action(this);"/><label>Ticket</label>
</div>
it works fine in firefox but doesn't work in internet explorer.
any ideas what it could be? the buttons basically display one of 2 options, a ticket or e mail, when clicking on the ticket it just doesn't show.
if you require any further information please let me know.
thanks
var tabs = document.getElementsByName("action_tab")
First, getElementsByName() is broken in IE. Rather use getElementsByTagName() and/or getElementById(). Or better, use jQuery and $('[name=action_tab]').
Second, this sounds like as <div name="action_tab"> and so on. The HTML <div> element doesn't have a specified name attribute and I doubt if a custom name attribute will work that way in IE with getElementsByName().
You don't state which DOCTYPE you're using (if any), but certainly with XHTML attributes have to have values, which your checked attribute doesn't have. You could try this:
<input type="radio" checked="checked" name="action_type" value="EmailActionDescription" onclick="toggle_action(this);"/><label>Email</label>
Since you don't post your toggle_action() code I can only guess that the problem is in that function. And probably if the function fails, the radiobutton selection routine is canceled.
What do you use the toggle_action() routine for?

Simple Javascript question

When I click on the button, the first time, everything works fine, but the second time, nothing happens. Why is that?
<form name="alert"><input type="text" name="hour"><input type="text" name="min"><input type="button" value="ok" onclick="budilnik(this.form)">
<script type="text/javascript">
function budilnik(form)
{
budilnik=1;
min=form.min.value;
hour=form.hour.value;
alert (min+' '+hour+' '+budilnik);
}
</script>
Learn to use Firebug. It'll help you immensely in the future.
budilnik=1;
This may sound crazy, but this is redefining the function budilnik to an integer, which breaks your form's onlick. If you preface this statement with keyword var, you will shadow the function but not overwrite it. When you do not specify the var keyword, variables are assumed to be global scope, which can cause issues (like this).
I used firebug to see that on the second click, "budilnik is not defined." If you had used this tool, you could have probably debugged this issue yourself.
The variable budilnik is shadowing the function budilnik. Change the name of the variable, and your function should work right every time.
In more detail:
First, JavaScript sees budilink defined as a function. When budilnik is executed, the value of budilnik is overwritten with the integer 1. So the next time JavaScript is told to execute budilink, it tries to execute 1, instead of the function that was there before.
Put the var keyword before your variable name.
I've tested the following code and it just works:
<form name="alert">
<input type="text" name="hour">
<input type="text" name="min">
<input type="button" value="ok" onclick="budilnik(this.form);">
<script type="text/javascript">
function budilnik(form)
{
var budilnik=1;
var min=form.min.value;
var hour=form.hour.value;
alert (min+' '+hour+' '+budilnik);
}
</script>
Change budilnik=1; to i_budilnik=1 or some other variable name .. by specifying budilnik=1; you are changing the definition from a function to a int val.
Alternatively you could try var budilnik=1; but not sure if that solves.

Categories