tags:

views:

81

answers:

2

In my javascript code I have

onchange="document.getElementById('user_name').value =  
 document.getElementById('theDomain').value + '\\' +
 document.getElementById('fake_user_name').value"

here backslash doesn't work. What is the problem? How should I write it?

example: I want to have "x.com\joe" by using domain name(x) and fakeusername (joe) but the result I get is just joe when I use '\'

+2  A: 

As you say it's in your JavaScript code rather than as an attribute on an HTML element,

onchange="document.getElementById('user_name').value =
    document.getElementById('theDomain').value + '\\' +
    document.getElementById('fake_user_name').value"

Is setting a string value, delimited by "". As the \\ is in a string, the value of the string is

document.getElementById('user_name').value = 
document.getElementById('theDomain').value + '\' +
document.getElementById('fake_user_name').value

which means that when that string is run as code, it is no longer valid - there is only one backslash, which escapes the closing single quote.

Either double-escape the back-slash ('\\\\'):

onchange="document.getElementById('user_name').value =
    document.getElementById('theDomain').value + '\\\\' + 
    document.getElementById('fake_user_name').value"

or use a function as an event handler instead of an evaluated string.

Pete Kirkham
+1  A: 

Pete Kirkham is correct: use a function instead of the string.

element.onchange=function(){
    var domain = document.getElementById('theDomain').value,
        name = document.getElementById('fake_user_name').value;
    document.getElementById('user_name').value = domain + "\\" + name;
};
David Murdoch