How to check the ID value of a tag and how often does it repeat with Jquery?

Asked

Viewed 681 times

2

Personal I have an excerpt of a code referring to image below inserir a descrição da imagem aqui

In the first div shows a list of students. In the second the students that the user chooses for his group, as he clicks on each student I have a function jquery that inserted the student in the group div and limits him to insert a maximum of 5 (outside the user himself) and the reverse process to remove the students from the group, every click sends him back to div students. I need to apply a business rule where necessarily the user should choose two students of each course, so I thought to put the ID of each course in the ID of li, but I don’t know how to read these id and allow only two students of each course in your group.

I tried to use .length with a if right after you check the maximum amount to make the comparisons, but it did not happen. ideas or examples to help please?

Code JQUERY:

  $(function(){
   $(".aluno").click(function(){ //EVENTO CLICK

    var c = 1; //CONTADOR
    $("#grupo .aluno").each(function(){
      c++;
    });

    if(($(this).parent().attr("id") == "lista") && c <=  5) { //VERIFICA EM QUAL DIV PERTENCE E QUANT. MÁXIMA
       $("#grupo").append(this); //ANEXA NA DIV GRUPO
       $("#grupo .aluno").addClass("selecionado"); //INSERIR CLASSE COM A COR DIFERENTE

    } else {
       $("#lista").append(this); //ANEXA NA DIV ALUNOS
       $("#lista .aluno").removeClass("selecionado"); //REMOVER CLASSE
    }

  });
});

HTML:

  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

  <link rel="stylesheet" href="style.css">

 <div class="lista-alunos">
    <h3></i>Alunos</h3>
    <ol id="lista">
      <li class="aluno" id="1">Gabriel | ENG.</li>
      <li class="aluno" id="1">Rafael | ENG.</li>
      <li class="aluno" id="1">Samuel | ENG.</li>
      <li class="aluno" id="1">Alex | ENG.</li>
      <li class="aluno" id="1">Ricardo | ENG.</li>
      <li class="aluno" id="2">Felipe | ADS.</li>
      <li class="aluno" id="2">Cesar | ADS.</li>
      <li class="aluno" id="2">Pedro | ADS.</li>
      <li class="aluno" id="2">Maria | ADS.</li>
      <li class="aluno" id="2">Ana | ADS.</li>
      <li class="aluno" id="3">Lucas | ARQ.</li>
      <li class="aluno" id="3">Miguel | ARQ.</li>
      <li class="aluno" id="3">David | ARQ.</li>
      <li class="aluno" id="3">Julia | ARQ.</li>
      <li class="aluno" id="3">Alice | ARQ.</li>
    </ol>
</div>

<div class="lista-grupo">
  <h3>Grupo</h3>
       <ol id="grupo">
            <li class="lider" id="1">Eu | ENG.</li>
      </ol>
</div>

CSS:

      .lista-alunos, .lista-grupo{
        position: relative;
        float: left;
        display: block;
        width: 270px;
        height: 270px;
        padding: 10px;
        margin-right: 10px;
        border: 1px solid #ccc;
        background-color: #F7F7F7;
      }
      #lista{
        overflow-y: scroll;
        height: 205px;
      }
      #lista, #grupo{
        padding-left: 20px;
        -webkit-touch-callout: none;
        -webkit-user-select: none;
        -khtml-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
      }
      .aluno, .lider{
        margin: 3px;
        padding: 4px;
        cursor: pointer;
      }
      .aluno{
        background: #CACACA; 
      }
      .selecionado, .lider{
        background: #A1B3A1;
      }
  • "I need to apply a business rule where the user must choose two students from each course" - you want to select two of each time or prevent selecting more than two of each course?

  • prevent selecting more than two from each course

  • Buddy, I don’t understand very well, do you want to tell which Ivs? Answers me here that when I do I edit with the result.

  • In the Group div must have two students of each course mandatory to validate. Example of a valid group: two ENG students, two ARQ and two ADS students

  • Can you explain the logic of selecionado? when and what is selected when you click?

  • It was a way that I found to change the color of the students entered in the group, and remove it in case it goes back to the student list. That is to say, it has a class in CSS . selected with green backgroud, when it goes to the group it receives this class, when it leaves the group it removes the class. I tried to add directly by style, but they changed the two lists when clicked

  • The leader also counts as a student in duplicates?

  • Buddy, the html and javascript that you provided not well formatted, it is complicated to tidy, please put the real code, so that I can adapt your code with the counter

  • yes the leader counts, it already comes when the page is loaded. in case it is the user himself

Show 4 more comments

3 answers

4


In each document (ie. in each "HTML page") the Ids must be unique. This is the fundamental difference between ID and class. ID is unique and class is to apply to element groups.

If that id is related for example to something that comes from the database you can store this information in the element in a field data-. So the element has the information you want and you can still group it together. A class would also work, depending on what you need, and as long as you can group.

In case you use data-id you can do so in jQuery/Javascript:

$(function() {
    $(".aluno").click(function() { //EVENTO CLICK
        var aluno = this;
        var campo = aluno.parentElement.id == 'lista' ? '#grupo' : '#lista';
        var alunosGrupo = $("#grupo li"); // se o lider não contar podes usar "#grupo .aluno"

        if (aluno.parentElement.id == 'lista') {
            var duplos = alunosGrupo.get().filter(function(el) {
                return aluno.dataset.id == el.dataset.id;
            });
            if (duplos.length > 1) return;
        }
        if (alunosGrupo.length <= 5) $(campo).append(aluno); //ANEXA NA DIV GRUPO
        else return;

        aluno.classList.toggle('selecionado');
    });
});

jsFiddle: https://jsfiddle.net/p3wb04k9/1/

  • 1

    Voteup, it worked perfectly here, I don’t know why in my js fiddle the javascript q it made available didn’t work

  • 1

    Yes in the system this information will come from the database, thanks for the help is functional yes. I need to study the methods you used to understand line by line, haha. But thank you Sergio

1

the first error in your html, is that your id repeats, Embrese that the id serves to identify the HTML element and not the course.

if you need to add values related to your business in HTML, use properties data-custom, as an example data-curso='1' or data-aluno='33'

once done, you can count the amount of students in the div#grupos who are in the same course, and do not move the student to the group if they meet the condition.

in the example below I am assuming that the logged-in student has data-aluno='0', but you can create a new property like data-self='true'

the rest of the logic, is to move the student to his old possible on the other list (I am ordering by id of aluno)

var alunos = document.querySelector("#alunos .content");
var grupos = document.querySelector("#grupos .content");

var pessoas = document.querySelectorAll(".content div[data-aluno]");
var moverPessoa = function (atual, destino, id) {
  var irmaos = destino.querySelectorAll("div[data-aluno]");
  irmaos = [].filter.call(irmaos, function (aluno, indice) {    
    return parseInt(atual.dataset.aluno) < parseInt(aluno.dataset.aluno);
  });
  
  if (irmaos.length == 0) {    
    destino.appendChild(atual);
  } else {    
    destino.insertBefore(atual, irmaos[0]);
  }
}

var onPessoaClick = function (event) {
  var atual = event.target;
  var id = parseInt(atual.dataset.aluno);
  var origem = atual.parentElement;
  var destino = origem == alunos ? grupos : alunos;
  
  if (id == 0) {
    alert('Não é possivel remover a si mesmo do Grupo');
    return;
  }
  
  if (origem == alunos) {
    var pessoas = destino.querySelectorAll("div[data-aluno]");
    var mesmoCurso = [].filter.call(pessoas, function (aluno, indice) {    
      return atual.dataset.curso == aluno.dataset.curso;
    });
    if (mesmoCurso.length == 2) {
      alert('Não é possivel mover mais alunos deste curso para o grupo');
      return;
    }
  }
    
  moverPessoa(atual, destino, id);
};

[].forEach.call(pessoas, function (pessoa, indice) {
  pessoa.addEventListener("click", onPessoaClick);
});
html, body {
  position: relative;
  width: 100%;
  height: 100%;
  margin: 0px;
  padding: 0px;
  background-color: whitesmoke;
}

.container {
  position: absolute;
  margin: 10px;
  width: calc(50% - 20px);
  height: calc(100% - 20px);
  background-color: white;
  box-shadow: 0px 0px 10px black;
  border-radius: 5px;
  overflow: auto;
}

#alunos {
  left: 0px;
}

#grupos {
  right: 0px;
}

.container header {
  position: absolute;
  top: 0px;
  width: 100%;
  height: 40px;
  line-height: 40px;
  text-align: center;
  font: bold 30px Cambria;
  background-color: gainsboro;  
}

.container .content {
  position: absolute;
  width: 100%;
  top: 40px;
  bottom: 0px;
  overflow: auto;
}

.container .content div {
  width: 100%;
  height: 40px;
  line-height: 20px;
  font: normal 20px Calibri;
  padding: 10px;
  border-bottom: 1px solid gainsboro;
  box-sizing: border-box;
  cursor: pointer;
}
<section id="alunos" class="container">
  <header>Alunos</header>
  <div class="content">
    <div data-aluno="1" data-curso="1">Gabriel | ENG.</div>
    <div data-aluno="2" data-curso="1">Rafael | ENG.</div>
    <div data-aluno="3" data-curso="1">Samuel | ENG.</div>
    <div data-aluno="4" data-curso="1">Alex | ENG.</div>
    <div data-aluno="5" data-curso="1">Ricardo | ENG.</div>
    <div data-aluno="6" data-curso="2">Felipe | ADS.</div>
    <div data-aluno="7" data-curso="2">Cesar | ADS.</div>
    <div data-aluno="8" data-curso="2">Pedro | ADS.</div>
    <div data-aluno="9" data-curso="2">Maria | ADS.</div>
    <div data-aluno="10" data-curso="2">Ana | ADS.</div>
    <div data-aluno="11" data-curso="3">Lucas | ARQ.</div>
    <div data-aluno="12" data-curso="3">Miguel | ARQ.</div>
    <div data-aluno="13" data-curso="3">David | ARQ.</div>
    <div data-aluno="14" data-curso="3">Julia | ARQ.</div>
    <div data-aluno="15" data-curso="3">Alice | ARQ.</div>
  </div>
</section>

<div id="grupos" class="container">
  <header>Grupo</header>
  <div class="content">
    <div  data-aluno="0" data-curso="1">Eu | ENG.</div>
  </div>
</div>

  • Thanks for the tips, it’s functional as well as Sergio’s. And good to see different ways to solve I’m gaining experience

0

create a variable and place the li inside with

var li = document.getElementById("id_da_li");

then do

li.getAttribute("id"); 

then you make a if saying that if the id is equal to 1 add in the array with the method .push(li); and adds to the div Then you count how many elements you have in the array and makes another if saying that if you have more than two elements you can no longer add any

  • Demetrius, in HTML there can be no duplicate Ids...

Browser other questions tagged

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