0

I've tried writing this several different times, but it's just not working. Is there any evident error from the code below? I'm trying to get it to insert a new form input with a changing name value.

<script>
    $("document").ready(function(){
        console.log('wtf is going on');
        var i = 0;
        var insert = '<div class="form-group"> +
                <label>Categories</label>+
                <input type="text" class="form-control" name="category' +i+'" value="test"></div>';
        $(".lolz").click(function(){
            i++;
            $(".lolz").before(insert)});
    });
</script>
PG1
  • 1,220
  • 2
  • 12
  • 27
user3340037
  • 731
  • 2
  • 8
  • 23
  • Newlines in a JS string will give you problems. –  Jun 17 '14 at 08:05
  • 1
    Multiline strings in JavaScript aren't supported like that. See http://stackoverflow.com/questions/805107/creating-multiline-strings-in-javascript. Next time, open your browsers console using F12, and you'll see these sorts of errors straight away. – Matt Jun 17 '14 at 08:05

2 Answers2

1

The problem is in your newlines in the insert string:

var insert = '<div class="form-group">
              <label>Categories</label>
              <input type="text" class="form-control" name="category' + i +
             '" value="test"></div>';

JavaScript doesn't support multi-line strings, without telling the interpreter explicitly that the string is multi-line.

Try replacing those lines with:

var insert = '<div class="form-group"> \
              <label>Categories</label> \
              <input type="text" class="form-control" name="category' + i + 
             '" value="test"></div>';

The slash (\) "escapes" the following line-break, which basically tells the JavaScript interpreter "This string continues on the next line".

A slightly more maintainace-friendly way, would be to use string concatenation, like this:

var insert = '<div class="form-group">' +
             '<label>Categories</label>' +
             '<input type="text" class="form-control" name="category' + i + 
             '" value="test"></div>';
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
-1

try this way....

var insert = '<div class="form-group">'
              insert += ' <label>Categories</label>'
               insert += '<input type="text" class="form-control" name="category' +i+'" value="test"></div>';
K.K.Agarwal
  • 846
  • 5
  • 10