Multi-line string insert using jQuery

$("#addSelect").click(function() {
        $("#optionsForm").after("Hello world.");
} );

This works.

$("#addSelect").click(function() {
        $("#optionsForm").after("<tr>
    <td><input type="text" class="optionField" value="Options" /></td>
    <td>
        <ul class="option">
            <li><select><option>Value..</option></select></li>
        </ul>
    </td>
</tr>");
} );

Something like this doesn't.

In Chrome, I get the error "Unexpected token ILLEGAL". After Googling I've discovered my teeny brain doesn't know much about javascript and multi-lines. So I added '\' to then end of each line. Yet, I now get the error "Unexpected identifier".

I'd like this to not be as difficult as I'm making it :)

Answers:

Answer

Use back ticks ` to start and finish the string

$("#addSelect").click(function() {
    $("#optionsForm").after(`<tr>
    <td><input type="text" class="optionField" value="Options" /></td>
    <td>
        <ul class="option">
            <li><select><option>Value..</option></select></li>
        </ul>
    </td>
</tr>`);
} );

Answer

Change all the double quotes for the attributes to single quotes.

$("#addSelect").click(function() { 
        $("#optionsForm").after("<tr> \
    <td><input type='text' class='optionField' value='Options' /></td> \
    <td> \
        <ul class='option'> \
            <li><select><option>Value..</option></select></li> \
        </ul> \
    </td> \
</tr>"); 
} ); 
Answer

a cleaner approach is to use <script> tag

https://stackoverflow.com/a/12097933/1416458

<script id="stuff_you_want" type="text/plain">
<tr>
    <td><input type="text" class="optionField" value="Options" /></td>
    <td>
        <ul class="option">
            <li><select><option>Value..</option></select></li>
        </ul>
    </td>
</tr>
</script>

<script>

    // pure javascript
    var text = document.getElementById("stuff_you_want").innerHTML ;

    //or using jQuery... (document ready for safety)
    $(document).ready(function() {

        var text = $("#stuff_you_want").html(); 

    }

</script>

content-type must be set for html 4.0 compliance.

Answer

I prefer to use something like this:

$('<tr bgcolor="#ffffe6"><td></td><td colspan="8" id="orderNotes">'
    + inputNotes.val() + '</td> <td>' + todayStamp
    + '</td> </tr>')

I feel like it's clean the + concatenation allows you to know we're working with the same black and it gives you the flexibility of adding variables.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.