Forum Moderators: open

Message Too Old, No Replies

Can attribute be added to form inputs using JavaScript

autocomplete="off"

         

Fotiman

2:24 pm on May 10, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



There is a non-standard attribute which allows some browsers to *not* save values in an auto complete list:

autocomplete="off"

This can be used in the form tag to apply to all inputs in the form, or on individual inputs to apply only to that input. Good for fields that store sensitive data, like credit card numbers.

Anyway, this attribute is not standard, so putting it in your document will cause it to fail validation. What's the best way to append this using JavaScript (so the document remains valid)?

Fotiman

2:53 pm on May 10, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



To answer my own question, yes, it can be done. Here's how:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset:utf-8">
<title></title>
<script type="text/javascript">
function setNodeAttr( nodeObj, attrName, attrVal )
{
// No sanity checks here. Verify nodeObj before calling this.
var attributeNode = nodeObj.getAttributeNode( attrName );
if ( attributeNode )
{
attributeNode.value = attrVal;
}
else
{
nodeObj.setAttribute( attrName, attrVal );
}
}
function disableAutoComplete( idref )
{
var obj = document.getElementById( idref );
if(!obj ) return;
setNodeAttr( obj, "autocomplete", "off" );
}
</script>
</head>
<!-- This works using the form id (fff) to disable autocomplete for all fields,
or using individual ids of inputs (like sensitivedata) -->
<body onload="disableAutoComplete('sensitivedata');">
<form action="#" method="get" id="fff">
<div>
<input type="text" name="sensitivedata" id="sensitivedata">
<input type="text" name="notsensitive" id="notsensitive">
<input type="submit" name="submit" value="Submit">
</div>
</form>
</body>
</html>