0

I have a list with names, each name has a sublist with subitems.
I need to pass those subitems to the table when I click on the name.
Here is an example, try to expand the first name.
But if I click on it again, it will keep adding that value to different cells of the table. How may I add this only once ? Or always at the same place?

Also, I have some attributes of the disciplines:

data-time = The time the discipline start;
data-id = The ID of that discipline (all brought from database);

My Code:

/*JQuery*/
$(document).ready(function(){
    $(".prof-list h3").click(function(event){
        var obj = event.target; 
        var disciplina_id = $(this).next().find('li').data('id');
        var disciplina_hora = $(this).next().find('li').data('time');
        if(disciplina_hora == "14:30:00"){
            var myRow = document.getElementById("prof-table").rows[3];
            myRow.insertCell(1).innerHTML = $(this).next().find('li').text();
        }
        else if(disciplina_hora == "08:30:00"){
            var myRow = document.getElementById("prof-table").rows[1];
            myRow.insertCell(1).innerHTML = $(this).next().find('li').text();   
        }

        if(obj.nodeName == "H3")
            $(this).next().slideToggle();//Aplica efeito slide
        //$("#list_prof").html("clicked: " + event.target.nodeName ); //Teste
    })
})

1 Answer 1

1

use .cells[] to update cell content

if(disciplina_hora == "14:30:00"){
    var myRow = document.getElementById("prof-table").rows[3];

    // insert if `myRow` only has 1 cell
    if(myRow.cells.length <= 1)
      myRow.insertCell(1);

    // use `cells[1]` to update the 2nd cell content 
    myRow.cells[1].innerHTML = $(this).next().find('li').text();
}

Edit Update

if(myRow.cells.length <= 1){
    $(this).next().find('li').each(function(idx, elm) {
      myRow.insertCell(idx + 1);    
      myRow.cells[idx + 1].innerHTML = $(elm).text();
    });
} else {
    while(myRow.cells.length > 1)
        myRow.deleteCell(1);
}
Sign up to request clarification or add additional context in comments.

3 Comments

hey man, try again in codepen please. If you try to move items of a teacher that has more than one discipline, all the discipline goes to the same place of the <td>. Is there a way to make something like a foreach ?
Perfect ! You Rock !! If it's not too much, could you explain to me how idx and elm has value how they are something. I mean, you just write them as parameter but how do they have some value, some meaning ... ?
You're the best, man. Sorry for ask this kind of thing but, I'll need to make some change on this later, make something more complex (is there a way to tag you in the question) ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.