Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to put if condition in jquery's append function

i have trapped in a jquery function, all i want is to append some divs using jquery's append function, but the problem is that i want to put some if conditions in this function,

here is my working code without condition

$( "#some-div-container" ).append( 
                                  "<div>name 1" +
                                      "<a href=\"#\">" +
                                           "<div id=\"add\">Add</div>" +
                                      "</a>" +
                                      "<div>Available</div>" +
                                  "</div>"
                                );

i am using jquery's ajax function having some json response, so i want just that, let say if(response == 1) then execute the code inside it, i am trying using condition,

 $( "#some-div-container" ).append( 
                                  "<div>name 1"
                                  if(response == 1) {    
                                     +"<a href=\"#\">" +
                                           "<div id=\"add\">Add</div>" +
                                      "</a>"
                                  }
                                      + "<div>Available</div>" +
                                  "</div>"
                                );

is it possible? Any help will be appreciated, an error occured when i put this condition "my some other javascript function is not defined", works perfect without condition

like image 303
Irfan Ahmed Avatar asked Nov 21 '25 10:11

Irfan Ahmed


2 Answers

Build your string beforehand, by using a variable:

var elements = "<div>";
if (someCondition) {
  elements += "<a href='#'>some link</a>";
}
elements += "</div>";

Or, a more specific example:

var elements = "<div>name 1";
if(response == 1) {    
  elements += 
    "<a href='#'>" +
      "<div id='add'>Add</div>" +
    "</a>";
}
elements += "<div>Available</div>";
elements += "</div>";

Then append the resulting string:

$("#some-div-container").append(elements);
like image 187
Grant Thomas Avatar answered Nov 25 '25 00:11

Grant Thomas


You could acheive that in the following manner:

$('#some-div-container').append(
    '<div>name 1' + 
    (response == 1 ? '<a href="#"><div id="add">Add</div></a>' : '') +
    '<div>Available</div></div>'
);

Demo

But I think it would be neater to do something like this

var div = $('<div/>', { text: 'name 1' });
if(response == 1) {
    div.append($('<a/>', { href: '#' }).append($('<div/>', { id: 'add', text: 'Add' })));
}
$('<div/>', { text: 'Available' }).appendTo(div);
div.appendTo('#some-div-container');

Demo

like image 38
David Hedlund Avatar answered Nov 24 '25 23:11

David Hedlund



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!