traverse array and insert break line jquery

Asked

Viewed 765 times

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’s inserting the asides when he arrives in the 4th he inserts the line break only in the 6 7 he inserts again, in which case I need him to enter in the 4 after 8 after 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>
  • I don’t know if I understand but the idea is to show a drawn result or really every four indices of a list depending on how the answer may be different

  • ola the idea is every 4 indices even only one at each click.

  • javascript already know how scroll could add asides (html). so you can understand that you are adding to the array of elements (A) the very item that calls the event click (referencing this) and again adding the "A" when you push the variable store at this point this empty realize

  • already inserted html blz in this case I need to generate 3 asides in 4 breaks the line, generates 5, 6, 7 in 8 break line...

1 answer

0


Well the example below is well commented but I highlight the fact of storing the indexes adding them to the beginning because in this example these indexes "stored" are returned by the method pop that returns and removes the last item from the array.

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

considerations Consider that your student list will be served by php then 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) you simply check whether the item’s index in the array is a multiple of four using the expression ([i][0] % 4 === 0) but it is worth noting that an array in javascript always begins with 0 for a better observation 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>


edited With respect to users who will already read this answer I will keep the original answer so that they do not get lost in the comments made based on it.

// 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>

  • ola I adapted your code, as you can see the title of the post I want to insert a line break after the "Asides" which are generated dynamically when clicking, only I want to insert the line break only after the "Asides" 4, 8, 12, etc...

  • new code $('body'). on('click', 'a. add_student', Function() { var aside = $(this). Parent(). Parent(). Children('aside'); $(this). Parent(). Parent(). append('<aside id="inner_form">' + aside.html() + '</aside>'); var store = []; aside.each(Function() { store.push($(this). html()); }); for (var i = 4; i < store.length; i += 4) { store.unshift(store[i]); } if (store.length > 0) { store.pop(). append('<br /><hr /><br />'); } Else { Return false; } });

  • Good if it helped blz..

  • Actually it’s adding in all I want to add to the 4 after 8 after 12 and so on, there’s something silly missing.

  • Well I did not understand the logic that you used in this code that you put here in the comments but I believe that you should initially store the results (from 4 in 4) then search when there is a "click" event does not run everything in the event. And to store follows this logic "store.unshift(contarAside[i]+'<br>');"

  • I adapted your code to jquery I create a vector of asides and then make the request to insert a line break after 4 in 4 asides, but so is inserting in all, I am not getting.

  • ta I think I pulled... the arrays should be out of the scope of the click event.. see this print and tell me if this solves https://i.stack.Imgur.com/Jh0qg.png

  • note that: one of the loops should store in reverse order because the array pop function returns and removes the last item from the array, so if it is not it will bring the inverse result.

  • our followed your logic so now you are inserting in all from the first and I need you to enter from the 4 after 8 ...

  • hum... I do not consider my logic wrong it searches for 4 in 4 items of the array "A" and inserted in the array "B" which in turn is used in the event click to display the items of this array (B) at the same time it deletes them to not conflict with the next event. the example in my reply ta functional

  • consider editing your question (the code in it) by adding a more substantial part of what you use. That doesn’t mean exposing all the code but only the essential so maybe we can come up with a result

  • updated the question if you can help me in waiting.

  • apologies for the lack of information insert the html Cod.

  • 1

    Bro I don’t even know how to thank you that’s what I need, solved my problem, I used to use in other ways thank you very much

Show 9 more comments

Browser other questions tagged

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