Mbrouwer88
Mbrouwer88

Reputation: 2292

Using new lines in javascript jquery

I am using

$('#'+type+'name'+id).hide().html('ghj').fadeIn(150);

Which works fine. But when I use

$('#'+type+'name'+id).hide().html('
A lot of html code
').fadeIn(150);

The function does not work anymore. Since I want to keep the function tidy I want to put the HTML there in multiple lines. Why doesnt this work?

EDIT: Still does not work:

function Rename(type,id,content){
$('#'+type+'name'+id).hide().html(' '+
    '   <td height=\"20\" valign=\"middle\">'+
    '       <span onclick=\"RenameDo(\'notify\',\''+id+'\',''+content+'')\">'+
    '           <img title=\"Wijzigen\" class=\"LinkImage\" src=\"/common/images/save.png\">'+
    '       </span>'+
    '   </td>'+
    '   <td valign=\"middle\" rowspan=2>&nbsp;fghfgh</td>'+
' ').fadeIn(150);

}

Upvotes: 1

Views: 63

Answers (2)

ATOzTOA
ATOzTOA

Reputation: 36000

Just use + to concatenate long strings:

$('#'+type+'name'+id).hide().html(' ' + 
'A lot of html code' +
' ').fadeIn(150);

Or use \ to escape newline:

$('#'+type+'name'+id).hide().html('\
A lot of html code\
').fadeIn(150);

Update

For the specific string, use this:

function Rename(type,id,content){
    $('#'+type+'name'+id).hide().html(' '+
        '   <td height="20" valign="middle">'+
        '       <span onclick="RenameDo(\'notify\',\'' + id + '\',\'' + content + '\')">' +
        '           <img title="Wijzigen" class="LinkImage" src="/common/images/save.png">'+
        '       </span>'+
        '   </td>'+
        '   <td valign="middle" rowspan=2>&nbsp;fghfgh</td>'+
    ' ').fadeIn(150);
}

Upvotes: 4

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324810

There are two ways to do this, the "hack way that works anyway", and the "proper way".

Hack way:

$("#"+type+"name"+id).hide().html("\
A lot of html code\
").fadeIn(150)

Explanation: By adding a backslash at the end of the line, you are effectively "escaping" the newline so it is ignored instead of an unterminated string constant.

Proper way:

$("#"+type+"name"+id).hide().html(
"A lot of html code\n"
+"Just adding some more\n"
+"Because whitespace outside of strings is fine."
).fadeIn(150)

Upvotes: 1

Related Questions