Cannot create newline with alert box

Discussion in 'JavaScript' started by chuckdawit, Jun 8, 2007.

  1. #1
    I can't separate my strings onto new lines using the alert box. I want to separate my phone numbers onto new lines and then print them in the alert box like so:

    <A HREF='javascript:(function(){
    var s = "";
    for (var i = 0; i < phoneArray.length; i++) {
    s += phoneArray + "\n";
    }
    alert(s);
    } ) ()'>Phone Numbers</A>

    I've tried every combination I can think of (single, dubble quotes, \n, \r, etc) nothing will split them in the result string. And I reload the page every time. Do I need to do something else?
     
    chuckdawit, Jun 8, 2007 IP
  2. ajsa52

    ajsa52 Well-Known Member

    Messages:
    3,426
    Likes Received:
    125
    Best Answers:
    0
    Trophy Points:
    160
    #2
    Probably you're getting some javascript error. Check your javascript console.
    Working example using letters and numbers:
    
    <html>
    <body>
      <a href="javascript:alert('a'+'\n'+2+'\n'+'b');">test</a>
    </body>
    </html>
    
    Code (markup):
     
    ajsa52, Jun 9, 2007 IP
  3. krt

    krt Well-Known Member

    Messages:
    829
    Likes Received:
    38
    Best Answers:
    0
    Trophy Points:
    120
    #3
    So you are getting an alert box with no new lines between the phone numbers? I tried your code in the address bar and it works fine (provided I use dummy data), e.g.:
    javascript:var s = ""; for (var i = 0; i < 3; i++) { s += "test" + "\n"; } alert(s);
    Code (markup):
    Copy paste that into your address bar in your web browser, (press enter) and tell me if you get the new lines. If so, can you show more of the code. If not, what browser are you using.
     
    krt, Jun 9, 2007 IP
  4. chuckdawit

    chuckdawit Peon

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    I had to put another \ character in front of the string like this: "\\n". Now it works. Can anyone explain why it needs two \ chars?
    -Chuck
     
    chuckdawit, Jun 9, 2007 IP
  5. ajsa52

    ajsa52 Well-Known Member

    Messages:
    3,426
    Likes Received:
    125
    Best Answers:
    0
    Trophy Points:
    160
    #5
    You need two \\ when you are generating javascript code from another language, to achieve the '\' character on new source (javascript).
     
    ajsa52, Jun 9, 2007 IP