mstojanov
mstojanov

Reputation: 185

jQuery Stop duplicate append

What i'm trying to do here i have 1 select box and one input.

The select box have 3 options with values 1,2 and 3 and the input is in div with id INPUT.

What i want here is when i select the options with value 3 to remove the whole div tag with id INPUT, and then when i click again example on 1 or 2 the DIV tag to append again. But when i'm clicking on 1 or 2 the div tag is appending again and again.

Is there is a chance to check if the div tag exist and not to append.

Here is my jQuery :

$('select').change(function(){
            var val = $(this).val();
                if(val == '3'){
                    $('#INPUT').remove();
                    }

                if(val !== '3'){
                $('.valuta').before('<div id="INPUT"><input type="text"  class="price"></div>');

                    }
                });

Any help will be appreciated. Thanks.

Upvotes: 0

Views: 4416

Answers (2)

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18344

Yes, it's possible. Change this:

if(val !== '3'){

to this:

if(val != '3' && $("#INPUT").size() == 0){

This way, we're asking if there is already a div with id = INPUT, if there is none, then we add one.

Cheers

Upvotes: 3

Arun P Johny
Arun P Johny

Reputation: 388316

Check whether the element with the id INPUT already exists before adding a new one

if (val != '3' && !$('#INPUT').length) {
    $('.valuta').before('<div id="INPUT"><input type="text"  class="price"></div>');
}

Demo: Fiddle


Also you can fine tune the if condition because if the value is not 3 then you want to have the input field so there is no need for the second if condition just use else block in the first condition

$('select').change(function () {
    var val = $(this).val();
    if (val == '3') {
        $('#INPUT').remove();
    } else if (!$('#INPUT').length) {
        $('.valuta').before('<div id="INPUT"><input type="text"  class="price"></div>');
    }
})

Demo: Fiddle

Upvotes: 2

Related Questions