go through array and insert jquery line break

1

This application does not work as expected.

var storeElements = [];     var store = [];

$('body').on('click', 'a.add_aluno', function () {

    var aside = $(this).parent().parent().children('aside');
    $(this).parent().parent().append('<aside id="inner_form">' + aside.html() + '</aside>');

    aside.each(function () {
        storeElements.unshift($(this));
    });

    for (var i = 4; i < storeElements.length; i += 4) {
        store.push(storeElements[i]);
    }

    if (store.length >= 4) {
        //Aqui preciso inserir quebra de linha a partir do 4º aside gerado, e o proximo é 8 depois 12, etc..
    }
});

So he inserts the asides when he arrives in the 4th he inserts the line break only that in 6 7 he inserts again, in that case I need to insert in the 4 after 8 then 12, etc ...

html

<form id="boletin_cad" action="env_boletin.php" method="POST">

    <aside id="inner_form">
        <select name="aluno">
            <option value="">Selecione o aluno</option>
            <?php
            $pega_alunos = $db->prepare("SELECT * FROM efcol_cadastro WHERE status_conta = ? ORDER BY nome");
            $pega_alunos->execute(array('Ativo'));
            while ($dados_alunos = $pega_alunos->fetch()) {
                echo '<option value="' . $dados_alunos['id'] . '">' . $dados_alunos['nome'] . '</option>';
            }
            ?>            
        </select><br />
        <select name="materia">
            <option value="">Selecione a Matéria</option>
            <option value="01">LIBERTAÇÃO I</option>
            <option value="02">REGIÕES DE CATIVEIRO</option>
            <option value="03">H. ESPIRITUAL</option>
            <option value="04">ESQ. JEZABEL</option>
            <option value="05">ABORTO</option>
            <option value="06">ADULTÉRIO</option>
            <option value="07">DIVÓRCIO</option>
            <option value="08">LIB. SEXUAL I</option>
            <option value="09">LIB. SEXUAL II</option>
            <option value="10">INIMIGOS ESPIRITUAIS</option>
        </select><br />
        <legend>
            <span>Ano Letivo</span>
            <input type="text" name="ano" />
        </legend>
        <legend>
            <span>Semestre</span>
            <select name="semestre">
                <option value="1">1º</option>
                <option value="2">2º</option>
            </select></legend><br /><br />
        <legend>
            <span>Média</span>
            <input type="text" name="notas" />
        </legend>
        <legend>
            <span>Faltas</span>
            <input type="text" name="faltas" />
        </legend>
    </aside>
    <div class="botoes">
        <button name="add_media">Cadastrar</button>
        <a href="javascript:void(0);" class="add_aluno">+ ADD ALUNO +</a>
    </div>

</form>
    
asked by anonymous 29.10.2016 / 02:24

1 answer

0

Well, the example below is well-commented, but I would point out that storing the indexes by adding them to the startup because in this example these "stored" indexes are returned by the pop method that returns and removes the last item from the array. p>

For my failure to supply element select via php I created a false list of students with javascript even just for example, ignore it. However, it is this list that defines the possible total number of items to be inserted in the example: If the class of students (returned from the DB) has 16 students this is the maximum number. And so on.

Considerations Consider that your list of students will be served by php so replace this section:

// define o número para o loop reverso
var i = listaAluno.length;

For this:

// define o número para o loop reverso
var i = $('#inner_form select[name=aluno]').length;

In this example, instead of creating a sautéed loop (which was not working) simply check if the index of the item in array is multiple of four using the expression ([i][0] % 4 === 0) It is worth noting that an array in javascript always starts with 0 for a better observation I added colors and as the proposal of the question elements br and hr every four entries is this.

edited with jquery

/**
 * como não pude abastecer uma lista de alunos via php este trecho prove
 * uma lista "falsa" simplesmente para criar uma quantia de exemplo (20 alunos)
 */
var listaAluno = [
    {id:1,name:'Ana'},
    {id:2,name:'Paula'},
    {id:3,name:'Analize'},
    {id:4,name:'Moises'},
    {id:5,name:'Aragao'},
    {id:6,name:'Paulo'},
    {id:7,name:'Pedro'},
    {id:8,name:'Joao'},
    {id:9,name:'Carol'},
    {id:10,name:'Atila'},
    {id:11,name:'William'},
    {id:12,name:'Carlos'},
    {id:13,name:'Eduardo'},
    {id:14,name:'Andre'},
    {id:15,name:'Rafael'},
    {id:16,name:'Benito'},
    {id:17,name:'Tavares'},
    {id:18,name:'Belize'},
    {id:19,name:'Andresa'},
    {id:20,name:'Rosangela'}
];
// abastece o select
for(var i=0; i<listaAluno.length; i++){
   $('#inner_form select[name=aluno]').append('<option value="'+listaAluno[i].id+'">'+listaAluno[i].name);
}

// armazene fora do scopo do evento "click" um objeto array
var store = [];

// captura o html do aside
var aside = $('#inner_form').html();

// define o número para o loop reverso
var i = listaAluno.length;

// faz o loop reverso
for (;i--;) {
     // verifica se o indice do item é multiplo de 4
     if([i][0] % 4 === 0){
        // caso seja adiciona br hr etc...
        store.unshift('<aside style="background-color:green;" id="inner_form">' +aside+ '</aside><br><hr><br>');
     }else{
        //caso não seja multiplo de 4 não adiciona br hr etc...
        store.unshift('<aside style="background-color:red;" id="inner_form">' +aside+ '</aside>');
     }
}

// evento de click
$('body').on('click', 'span.add_aluno', function () {
    // verifica se há itens no array (store)
    if (store.length > 0) {
        // retorna e remove o ultimo item do array (store)
        $('#boletin_cad').append(store.pop());
    }
    // quando não houver mais itens não faz nada 
});
<form id="boletin_cad" action="env_boletin.php" method="POST">

    <aside id="inner_form">
        <select name="aluno">
            <option value="">Selecione o aluno</option>
            <!--
            <?php
            $pega_alunos = $db->prepare("SELECT * FROM efcol_cadastro WHERE status_conta = ? ORDER BY nome");
            $pega_alunos->execute(array('Ativo'));
            while ($dados_alunos = $pega_alunos->fetch()) {
                echo '<option value="' . $dados_alunos['id'] . '">' . $dados_alunos['nome'] . '</option>';
            }
            ?>
            -->
        </select><br />
        <select name="materia">
            <option value="">Selecione a Matéria</option>
            <option value="01">LIBERTAÇÃO I</option>
            <option value="02">REGIÕES DE CATIVEIRO</option>
            <option value="03">H. ESPIRITUAL</option>
            <option value="04">ESQ. JEZABEL</option>
            <option value="05">ABORTO</option>
            <option value="06">ADULTÉRIO</option>
            <option value="07">DIVÓRCIO</option>
            <option value="08">LIB. SEXUAL I</option>
            <option value="09">LIB. SEXUAL II</option>
            <option value="10">INIMIGOS ESPIRITUAIS</option>
        </select><br />
        <legend>
            <span>Ano Letivo</span>
            <input type="text" name="ano" />
        </legend>
        <legend>
            <span>Semestre</span>
            <select name="semestre">
                <option value="1">1º</option>
                <option value="2">2º</option>
            </select></legend><br /><br />
        <legend>
            <span>Média</span>
            <input type="text" name="notas" />
        </legend>
        <legend>
            <span>Faltas</span>
            <input type="text" name="faltas" />
        </legend>
    </aside>
    <div class="botoes">
        <button name="add_media">Cadastrar</button>
        <span style="cursor:pointer;" class="add_aluno">+ ADD ALUNO +</span>
    </div>

</form>







<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

editedWithrespecttouserswhowillalreadyreadthisresponseIwillkeeptheoriginalresponsesothattheydonotgetlostinthecommentsmadebasedonit.

// pre defina uma variavel para receber um objeto(array)
var store = [];

// assumindo que este indice ve de algum lugar (um db por exemplo)
var contarAside = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);

// faça o loop para arazenar os resultados
for (var i = 4; i < contarAside.length; i += 4) {
     // adicione ao inicio
     store.unshift(contarAside[i]);
}

// mostrar resultados
var view = document.getElementById('display');

// capture o botão
var btn = document.getElementById('init');

// adicione o evento
btn.addEventListener('click', function(){
    if(store.length > 0){
       view.innerHTML = "indice: "+store.pop();
    }else{
       view.innerHTML = "acabou";
    }
});
<button id="init">Clicar</button><br><br>

<div id="display" style="width:400px;height:200px;padding:1%;"></div>
    
29.10.2016 / 03:04