Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery append if doesn't exist

I would like to append a div only if it's not already there. I am trying with this but it doesn't work:

$('#method_id').on('change', function (e) {

    if ($(this).find("option:selected").data('method-column-id') != 1) {
        if ($('#column_message').next('div').length)
            $('#column_message')
                    .append('<div id="warning_message" class="alert alert-danger"><strong>Warning!</strong> Installed column and method do not match</div>');
    } else {
        $('.form-group').find('#column_message>.alert').remove();
    }
});

And if I remove the second if-clause, it gets appended every time I select an option which passes first if-clause

Here is the HTML

<!-- Warning message -->
<div class="form-group">
    <label for="group" class="col-md-2 control-label"></label>
    <div id="column_message" class="col-md-6">
    </div>
</div>
like image 300
Norgul Avatar asked Mar 19 '17 21:03

Norgul


3 Answers

In order to check if an element exists, you need to find a selector that matches only that element and check if the length of the jQuery object is equal to 0 or not, like so:

if ($('#unique-selector').length === 0) {
    // code to run if it isn't there
}
else {
    // code to run if it is there
}
like image 64
Michael Evans Avatar answered Nov 20 '22 19:11

Michael Evans


As you are appending div with id, you could just search if that div exists by calling :

if($("#warning_message").length > 0 ){
   $('.form-group').find('#column_message>.alert').remove();
}else{
   $('#column_message').append('<div id="warning_message" class="alert alert-danger"><strong>Warning!</strong> Installed column and method do not match</div>');
}

But if you would like to have more divs of alert, you could just search for class "alert" or so.

Another way without id ( probably better ) would be to use children() method

like image 35
Khobar Avatar answered Nov 20 '22 20:11

Khobar


the inner if should be if ($('#column_message').next('div').length===0) or if(!$('#column_message').next('div').length)

like image 1
Hadas Zeilberger Avatar answered Nov 20 '22 21:11

Hadas Zeilberger