0

I have looked at other questions about backslashes but none I've found provide a solution for me. I know backslashes escape characters in jQuery but I'm confused as to what they are doing in the following code. The code is taken from a course I am learning from but this part is not explained.

Here is the jQuery part of the code, from line 14 inside the append() function there is a backslash at the end of each line. The code works as is, if I remove the backslashes and keep the line breaks the code does not work, but if I remove the backslashes and remove the line breaks (everything gets bunched up together) it works again.

Can some please explain what is happening here?

EDIT: It's been pointed out that this is a duplicate question. I just hadn't been able to find that original question when initially looking.

countPos = 0;
            
$(document).ready(function(){
   console.log("Document ready called");
   $('#addPos').click(function(event){
        event.preventDefault();
        if (countPos >= 9) {
              alert("Maximum of nine position entries exceeded");
              return;
        }
        countPos++;
        console.log("Adding position "+countPos);
        $('#position_fields').append(
             '<div id="position'+countPos+'"> \
              <p>Year: <input type="text" name="year'+countPos+'" value=""/> 
               \
              <input type="button" value="-" \ 
                   onclick="$(\'#position'+countPos+'\').remove();return 
                   false;"></p> \
              <textarea name="desc'+countPos+'" rows="8" 
              cols="80"></textarea>\
              </div>'
               );
           });
                
       });
            
            
Niall
  • 87
  • 9

2 Answers2

0

These allow you to break a string into more than one line. Without them you would get an error.

smilebomb
  • 5,123
  • 8
  • 49
  • 81
  • Ahh ok, thanks. I thought it was escaping a line break or something but that makes sense. – Niall Aug 08 '18 at 21:06
0

It's used to go to next line without breaking the string. (To keep your code clean).

Instead of doing:

 $('#position_fields').append(
             '<div id="position'+countPos+'">'+
              '<p>Year: <input type="text" name="year'+countPos+'" value=""/>'+ 

              '<input type="button" value="-" '+ 
                   'onclick="$(\'#position'+countPos+'\').remove();return '+
                   'false;"></p> '+
              '<textarea name="desc'+countPos+'" rows="8" '+
              'cols="80"></textarea>'+
              '</div>'
               );
           });

As you can see, that way I have to break the string each time I go to the other line. So instead of breaking and concatenate the string, I can use the **** backslash

IsraGab
  • 4,819
  • 3
  • 27
  • 46