View Full Version : onFocus evet put in a variable

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


Please help me

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">';

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)
e[x] = attrs[x];

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

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() {
this.value = this.defaultValue;
size: 19