InnerHTML does not grab form values in Firefox?

February 26th, 2008   Filed Under Javascript, Tips & Tricks, browser, gyan, snippet  

Assignment of attribute values in Firefox, InnerHTML does not grab form values in Firefox:

Not all the attributes can be set by the .syntax using javascript as a permanent assignment. For example if you wan to assign a event handler onclick to an object, you need to use .setAttribute instead of .onclick.
The good thing is that setAttribute works in IE too.
So unless the attribute is set using .setAttribute, the DOM in Firefox or “Gecko” based browsers does not register the change.
I would like to demonstrate for clear understanding.

I have the following code:


<!doctype html public “-//w3c//dtd html 4.0 transitional//en”>
<html>
<head>
<title> new document </title>
<meta name=”generator” content=”editplus”>
<meta name=”author” content=”">
<meta name=”keywords” content=”">
<meta name=”description” content=”">
</head>
<BODY>
<form>
<input type=”text” name=”myText”/>
<input type=”button” value=”check” onclick=”checkIt(this)”/>
</form>
<script>
function checkIt(obj)
{
obj.form[’myText’].value = “hi there”;
alert(obj.form.innerHTML); // I EXPECT “myText” TO THROW THE VALUE AS AN ATTRIBUTE IN THIS ALERT
}
</script>
</body>
</html>


Here I expect “myText” to throw the value as an attribute in the alert, but the result is different for IE and FF.

In IE I get this:

ieih.jpg

and in FF I get this:

ffih.jpg

So to overcome this problem we need to use the following code:

function checkIt(obj)
{
obj.form[’myText’].setAttribute(”value”, “hi there”);
alert(obj.form.innerHTML); // I EXPECT “myText” TO THROW THE VALUE AS AN ATTRIBUTE IN THIS ALERT
}


Now it grabs the expected result.
Great to know that right?


Comments

Leave a Reply