pick element after being inserted into DOM with jQuery Append

Asked

Viewed 3,929 times

5

My page has a selectbox, with some segments, when a user selects a segment, through the event on change jQuery, he takes the value of <option> selected and inserts an Hidden input with the value of this option inside a div with append.

I need to make a loop for inside this particular div, and take the Hidden input element with a specific class, however, this input is inserted into the DOM after event with append.

if I loop for, and give a console.log it always returns 'Undefined'.

I need to take this input element in specific and see if the user entered the same 2x input with the same value to only then insert this input

I would like you to demonstrate to me a way to catch this element after the append.

here is an example of the code: http://jsfiddle.net/stzfd7t9/2/

HTML:

<label for="segmento">selecione um segmento</label><br>
<select name="" id="segmento">
    <option value="industria">industria</option>
    <option value="tecnologia">tecnologia</option>
    <option value="telecomunicações">telecomunicações</option>
</select>

<div id="result" class="filtro">

</div>

JAVASCRIPT:

/**
* limite de filtros
* padrão: 0;
*/
var filterLimit = 0;

/**
* container das etiquetas e input
*/
var filterContainer = $('#result');

var inputList = $('#result input[class="segment"]');

// quando uma opção for selecionada, adiciona a etiqueta
$('#segmento').on('change', function() {

    filterLimit++;

    var segValue = $('#segmento option:selected').text();

    if( filterLimit < 4 ) {

        // insere loop for aqui
        for( var i=0; i<= inputList.length; i++ ) {
            console.log(inputList)
        }

        // insere o elemento no DOM
        filterContainer.append('<input type="hidden" name="segment[]" value="'+ segValue +'" class="segment">');

        // insere a etiqueta 
        filterContainer.append('<div class="etiqueta">'+ segValue +' <a href="#" id="remove">x</a></div>');

    } else {

        alert('você só pode selecionar 3 filtros para segmento, remove um ou mais filtros e tente novamente');

    }
});
  • Why don’t you look up if that input already exists before to insert it?

3 answers

4

Note that I used the function each jQuery. It’s like a Foreach of PHP.

I take each value that is in the Hidden fields and compare it to the value that is being selected in the Combobox. If you have not added.

pick element after being inserted into DOM with jQuery Append

I took advantage and made the button that deletes the field, using the function On, that activates, so to speak, dynamically created field functions.

/**
* limite de filtros
* padrão: 0;
*/
var filterLimit = 0;

/**
* container das etiquetas e input
*/
var filterContainer = $('#result');

var inputList = $('#result input')

// quando uma opção for selecionada, adiciona a etiqueta
$('#segmento').on('change', function() {
    var boo = false;
    filterLimit++;
    
    var segValue = $('#segmento option:selected').text();
    
    if( filterLimit < 4 ) {
        
       // Se já existir um campo hidden com o valor selecionado
        $("input[name='segment[]']").each(function(){
            if(segValue == $(this).val())
               boo = true;              
        });
        
        if(!boo){     
            // insere o elemento no DOM
            filterContainer.append('<input type="hidden" name="segment[]" value="'+ segValue +'" class="segment">');
            
            // insere a etiqueta 
            filterContainer.append('<div class="etiqueta">'+ segValue +' <a href="#" class="remove" id="'+segValue+'">x</a></div>');
        }
        
    } else {
        
        alert('você só pode selecionar 3 filtros para segmento, remove um ou mais filtros e tente novamente');
        
    }
});

$(document).on('click', 'a.remove', function(){

   $("input[value='"+this.id+"']").remove();
   $(this).parent().remove(); 
});

        

  • worked, but there is a bug that after removing it still counts as if there were 3 elements added. I think you have to decrement the variable filterLimit

  • Bro, I edited my code. I hadn’t seen that there were two apends, but there’s a bug yet. You’ll find out.

  • "each function of JS" is wrong. I think you mean "jQuery". JS is .forEach() native since ES5.

  • @Sergio, why don’t you focus on answering the question ? Every time someone misses something, however simple it may be, you want to correct it.

  • 5

    @Diegosouza has already happened to me to answer questions that you also answered. I want to avoid "stealing the answer" and so I commented on what was wrong in your answer. If you correct this I will give +1 and I don’t need to answer. I received a lot of criticism when I started at Soen and learned from what they indicated to be wrong. I think it’s better we community members communicate with each other than give -1, then commented. If you find something wrong in my answers you can also comment clear. Conclusion: I commented willingly, to help improve the answer.

2

If you want to avoid a value being added twice you need to check the inputs you already have, and not add a new one if the value already exists in another input.

This check is done within the function that is run on change and you can simply search for an input with that value directly:

var jaExiste = filterContainer[0].querySelector('input[value="'+segValue+'"]');
if(jaExiste) return;

Notice that I used [0] for filterContainer is a jQuery object and so I extracted the DOM element.

Example: http://jsfiddle.net/aoe8f9vk/

1

I could not understand very well what you want, but it seems to me that you want to prevent the user to add 2 equal values, it is not?

If so, just create a array to store the values already entered and check before adding the values:

var filterLimit = 0,
    filterContainer = $('#result'),
    inputList = $('#result input');

var selected = new Array();

$('#segmento').on('change', function() {
    var segValue = $('#segmento option:selected').text();

    for ( var count = 0; count < selected.length; count++ ) {
        if (selected[count] == segValue) {
            alert('Você não pode adicionar 2 valores iguais');

            return false;
        }
    }

    if ( filterLimit < 3 ) {
        filterContainer.append('<input type="hidden" name="segment[]" value="' + segValue + '" class="segment">');
        filterContainer.append('<div class="etiqueta">' + segValue + ' <a href="#" id="remove">x</a></div>');

        selected.push(segValue);
        filterLimit++;
    } else {
        alert('você só pode selecionar 3 filtros para segmento, remove um ou mais filtros e tente novamente');
    }
});
  • sorry I should have devoted a little more time on my question to make it clear, I just want the user not to add the same value twice. the problem is that I could not check this because the input element was added dynamically.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.