Edward
Edward

Reputation: 3091

Using Jquery how can I add a HTML element based on JSON result

This is currently what I have if my Json object returns true then I add class error_back to #message else add class success_back. This works correctly, but now I want to add a button so I tried this:

Invalid Code

 $('#message').append((data.error === true) ? 
 '<input type='submit' name='submit' class='button' id='submit_btn' value='Go back' />' : '' ); 

Works correctly :

 $('#message').removeClass().addClass((data.error === true) ? 'error_back' : 'success_back').text(data.msg);

What is the correct way to add a button?

Upvotes: 0

Views: 156

Answers (3)

Blender
Blender

Reputation: 298392

If you look at the highlighted code, you will notice that it looks strange. You are using single quotes to wrap your string, but you're also using single quotes within the string.

Personally, I try to avoid constructing HTML strings as much as possible:

if (data.error) {
    $('<input />', {
        type: 'submit',
        name: 'submit',
        'class': 'button',  // `class` is a reserved keyword
        id: 'submit_btn',
        value: 'Go back'
    }).appendTo('#message');
}

Upvotes: 4

Sushanth --
Sushanth --

Reputation: 55750

That is invalid because of the Quotes .. You are using Single Quote ' to encase the string and also to encase the attributes.. So it will not interpret correctly.. To avoid that use Double Quotes " to fix it or need to escape the single Quotes..

$('#message').append(data.error  ? 
 "<input type='submit' name='submit' 
              class='button' id='submit_btn' value='Go back' />" : " " );

\OR Escape the Quotes

$('#message').append(data.error ? 
     '<input type=\'submit\' name=\'submit\' 
                  class=\'button\' id=\'submit_btn\' value=\'Go back\' />' : ' ' );

Upvotes: 1

Ram
Ram

Reputation: 144709

There is a syntax error in your code, you should not nest the single quotes.

$('#message').append( data.error ? '<input type="submit" name="submit" class="button" id="submit_btn" value="Go back" />' : '' ); 

Upvotes: 3

Related Questions