PDA

View Full Version : onFocus evet put in a variable



Dilruba
10-31-2007, 03:54 PM
onFocus event is working for the following code:


<input name="org" type="text" class="style4" id="org" maxlength="42" value="Test" onfocus="javascript:if(this.value=='Test')this.value='';" size="19">

But it is not working for the following position:


var strHtml1 = "";

strHtml1 = "<input name='org' type='text' class='style4' id='org' maxlength='42' value='Org' onfocus='javascript\:if(this.value==\'Organisation\')this.value=\'\'\;' size='19'>";

Is is there anything wrong for


onfocus='javascript\:if(this.value==\'Organisation\')this.value=\'\'\;'

Please help me

jscheuer1
10-31-2007, 04:13 PM
You've got your nested quoting all messed up, use:


var strHtml1 = '';
strHtml1 = '<input name="org" type="text" class="style4" id="org" maxlength="42" value="Org" onfocus="javascript\:if(this.value==\'Organisation\')this.value=\'\'\;" size="19">';

When nesting quotes, it is always easier to see what you are doing if you make the outermost delimiter also be the least used and the inner-most nested type of quote.

Also, for that to work like your first example does, it needs to be:


var strHtml1 = '';
strHtml1 = '<input name="org" type="text" class="style4" id="org" maxlength="42" value="Organisation" onfocus="javascript\:if(this.value==\'Organisation\')this.value=\'\'\;" size="19">';

Twey
10-31-2007, 04:42 PM
Or better (by far):
var e1 = document.createElement("input");
e1.name = e1.id = "org";
e1.type = "text";
e1.className = "style4";
e1.maxLength = 42;
e1.value = "Test";
e1.onfocus = function() {
if(this.value === this.defaultValue)
this.value = '';
};
e1.size = 19;Or perhaps (neater in my opinion):
function buildElement(tag, attrs, children) {
var e = document.createElement(tag);
for(var x in attrs)
if(attrs.hasOwnProperty(x))
e[x] = attrs[x];

if(children)
for(var i = 0, n = children.length; i < n; ++i)
e.appendChild(children);

return e;
}

var e1 = buildElement("input", {
name: "org",
id: "org",
type: "text",
className: "style4",
maxLength: 42,
value: "Organisation",
onfocus: function() {
if(this.value === this.defaultValue)
this.value = '';
},
onblur: function() {
if(!this.value)
this.value = this.defaultValue;
},
size: 19
});