Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If-statement inside jquery Append()

Inside my jquery Append() I wan't to run an IF-statement to include an image on all my objects except on the first one.

Like:

var i = 0;

$('#divDetailsForSelectedInfo').append(
    '<div class="roundedAndBoxShade leftResultObject" id = "' + value.Query.Id + '">'+
    '<div class="leftResultObject_inner">' +
if (i > 0){
   <img src="/img.jpg"/>;
}
'<div>asdf</div>');

The code is generated by Json+Jquery and then it is all appended on a div in my index-file. As far as I've been able to tell through immence google-ing this can't be done, but I might be wrong?

If it is indeed "impossible", could the :first selector in Jquery be used in some cool way?

like image 909
Solders Avatar asked Oct 15 '12 15:10

Solders


People also ask

How to put if condition in jQuery append function?

The easiest way I can think of to do this: $('#divDetailsForSelectedInfo'). append( function(i) { return '<div class="roundedAndBoxShade leftResultObject" id = "' + value.Query.Id + '">' + '<div class="leftResultObject_inner">' + (i > 0 ? '<img src="/img.

What is append in jQuery?

jQuery append() Method The append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.


3 Answers

A simpler solution:

var i = 0;
$('#somediv').append(
    'html before' + 
    (i > 0 ? '<img src="/img.jpg"/>': '') +
    'more html'
);
like image 194
Kostia Avatar answered Oct 11 '22 06:10

Kostia


var i = 0;
var str=''
if (i > 0){
  str =  '<img src="/img.jpg"/>;'
}
$('#divDetailsForSelectedInfo').append(
    '<div class="roundedAndBoxShade leftResultObject" id = "' + value.Query.Id + '">'+
    '<div class="leftResultObject_inner">' +str+'<div>asdf</div>');
like image 22
Salil Avatar answered Oct 11 '22 04:10

Salil


The easiest way I can think of to do this:

$('#divDetailsForSelectedInfo').append(
    function(i) {
        return '<div class="roundedAndBoxShade leftResultObject" id = "' + value.Query.Id + '">' + '<div class="leftResultObject_inner">' + (i > 0 ? '<img src="/img.jpg"/>' : '');
    });

JS Fiddle proof-of-concept.

like image 31
David Thomas Avatar answered Oct 11 '22 06:10

David Thomas