0

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 '\'

6
  • 1
    Could you elaborate a little on your results? What is the expected value? Commented Jun 9, 2010 at 12:02
  • 1
    What do you mean when you say that it "doesn't work", what happens, and how does that differ from what you expect? Do you get any error message? Commented Jun 9, 2010 at 12:02
  • 3
    Works well for me: jsbin.com/exaze3 , your problem is probably somewhere else. Is the code written directly in HTML source code, or are you writing it in another language? If so, you may need '\\\\'. Commented Jun 9, 2010 at 12:04
  • 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 '\\' Commented Jun 9, 2010 at 12:12
  • @erasmus - try to edit the question to add these details. What happens when you use + '-' +? What if you just used document.getElementById('theDomain').value? How do you explain your code working in the link I gave? Commented Jun 9, 2010 at 12:15

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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;
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.