Insert JavaScript line

4

I'm doing an example validation for a dynamic table and would like a bug help here. When I do the first insertion it gives right, when mute, it lets insert and duplicate.

$("button").click(function() {
  // alert('teste');
  var cont = 0;
  var count = $('#mytbody').children('tr').length;
  var vIdEmpresa = $('#selectEmpresa option:selected').val();
  var vEmpresa = $('#selectEmpresa option:selected').text();

  if (!count) {
    // console.log('vazio');
    var linha = '<tr class="selected" id="linha' + cont + '">' +
      '<td>' +
      '<input class="idemp" type="hidden" name="idempresa[]" value="' + vIdEmpresa + '">' + vEmpresa +
      '</td>' +
      ' </tr>'
    cont++;
    $('#mytbody').append(linha);
  } else {
    $(".idemp").each(function(index, value) {
      var vText = console.log($(this).text());

      if ($(value).val() == vIdEmpresa) {
        console.log('Empresa ja foi adicionada!');
      } else {
        var linha = '<tr class="selected" id="linha' + cont + '">' +
          '<td>' +
          '<input class="idemp" type="hidden" name="idempresa[]" value="' + vIdEmpresa + '">' + vEmpresa +
          '</td>' +
          ' </tr>'
        cont++;
        $('#mytbody').append(linha);
      }
    })
  }


});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.3.1.js"></script><divclass="container">
  <div class="row">

    <div class="col-md-10">
      <select class="form-control" id="selectEmpresa">
        <option value="1">Empresa 01</option>
        <option value="2">Empresa 02</option>
        <option value="3">Empresa 03</option>
      </select>
    </div>

    <div class="col-md-2">
      <button type="button" name="button">Adicionar</button>
    </div>

    <div class="col-md-12">
      <br>
    </div>

    <div class="col-md-12">
      <table class="table table-striped">
        <thead>
          <tr>
            <th>Empresa</th>
          </tr>
        </thead>
        <tbody id="mytbody">

        </tbody>
      </table>
    </div>
  </div>
</div>

Example

  $("button").click(function() {
  $('#selectEmpresa').change(function(){
    $('#msg').html('');
  });

  var vIdEmpresa = $('#selectEmpresa option:selected').val();
  var vEmpresa = $('#selectEmpresa option:selected').text();
  var mensagem = $('#msg');
  var linha = '<tr class="selected" id="linha' + vIdEmpresa + '">' +
        '<td>' +
        '<input class="idemp" type="hidden" name="idempresa' + vIdEmpresa + '" value="' + vIdEmpresa + '">' + vEmpresa +
        '</td>' +
        '<td>' +
        '<select class="form-control" id="autoriza">
          <option value="Sim">Sim</option>
          <option value="Não">Não</option>
        </select>'+
        '</td>' +
        '<td>' +
        '<input type="checkbox"  value="Sim">'+
        '</td>' +
        '<td>' +
        '<input type="radio" name="teste"  value="Sim"> Sim
         <input type="radio" name="teste" value="Nao"> Não'+
        '</td>' +
        ' </tr>'

  if($("tr#linha" + vIdEmpresa).length === 0) {
    $('#mytbody').append(linha);
  } else {
    $('#msg').html("<b class='text-danger'>&#9888; Empresa " + vIdEmpresa + " já foi adicionada!</b>");
  }
  });
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><scriptsrc="https://code.jquery.com/jquery-3.3.1.js"></script>
<div class="container">
  <div class="row">

    <div class="col-md-10">
      <select class="form-control" id="selectEmpresa">
        <option value="01">Empresa 01</option>
        <option value="02">Empresa 02</option>
        <option value="03">Empresa 03</option>
      </select>
    </div>

    <div class="col-md-2">
      <button type="button" name="button">Adicionar</button>
    </div>

    <div class="col-md-12">
      <span id="msg"></span><br>
    </div>

    <div class="col-md-12">
      <table class="table table-striped">
        <thead>
          <tr>
            <th>Empresa</th>
            <th>Autoriza</th>
            <th>Checa</th>
            <th>Opção</th>
          </tr>
        </thead>
        <tbody id="mytbody">

        </tbody>
      </table>
    </div>
  </div>
</div>
    
asked by anonymous 13.12.2018 / 14:06

2 answers

4

The problem is the tie you make:

$(".idemp").each(function(index, value) {

This loop is used to check if the company has already been added by traversing all the items in the table. The problem is that append of the company is being done before comparing and company added to all companies in the table. You need to modify your code to make append out of the verification loop, something like:

var empresaJaAdicionada = false;
$(".idemp").each(function(index, value) {
  var vText = console.log($(this).text());
  if ($(value).val() == vIdEmpresa) {
    console.log('Empresa ja foi adicionada!');
    empresaJaAdicionada = true;
  }
});
if (!empresaJaAdicionada) {
    var linha = '<tr class="selected" id="linha' + cont + '">' +
      '<td>' +
      '<input class="idemp" type="hidden" name="idempresa[]" value="' + vIdEmpresa + '">' + vEmpresa +
      '</td>' +
      ' </tr>'
    cont++;
    $('#mytbody').append(linha);
}

See that the empresaJaAdicionada variable was created to store whether the company was found in the table or not. The key point here is that the company addition code in the table will now run after forEach, thus ensuring that all companies have been queried and the new company could not be found and can be added.

The final version would look like this:

$("button").click(function() {
  // alert('teste');
  var cont = 0;
  var count = $('#mytbody').children('tr').length;
  var vIdEmpresa = $('#selectEmpresa option:selected').val();
  var vEmpresa = $('#selectEmpresa option:selected').text();

  if (!count) {
    // console.log('vazio');
    var linha = '<tr class="selected" id="linha' + cont + '">' +
      '<td>' +
      '<input class="idemp" type="hidden" name="idempresa[]" value="' + vIdEmpresa + '">' + vEmpresa +
      '</td>' +
      ' </tr>'
    cont++;
    $('#mytbody').append(linha);
  } else {
    var empresaJaAdicionada = false;
    $(".idemp").each(function(index, value) {
      var vText = console.log($(this).text());
      if ($(value).val() == vIdEmpresa) {
        console.log('Empresa ja foi adicionada!');
        empresaJaAdicionada = true;
      }
    });
    if (!empresaJaAdicionada) {
	    var linha = '<tr class="selected" id="linha' + cont + '">' +
		  '<td>' +
		  '<input class="idemp" type="hidden" name="idempresa[]" value="' + vIdEmpresa + '">' + vEmpresa +
		  '</td>' +
		  ' </tr>'
	    cont++;
	    $('#mytbody').append(linha);
    }
  }


});
<link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script><divclass="container">
  <div class="row">

    <div class="col-md-10">
      <select class="form-control" id="selectEmpresa">
        <option value="1">Empresa 01</option>
        <option value="2">Empresa 02</option>
        <option value="3">Empresa 03</option>
      </select>
    </div>

    <div class="col-md-2">
      <button type="button" name="button">Adicionar</button>
    </div>

    <div class="col-md-12">
      <br>
    </div>

    <div class="col-md-12">
      <table class="table table-striped">
        <thead>
          <tr>
            <th>Empresa</th>
          </tr>
        </thead>
        <tbody id="mytbody">

        </tbody>
      </table>
    </div>
  </div>
</div>

NOTE: There is a more elegant way to do this check. One is to create a business vector and manipulate it while adding business, rather than checking in the DOM if the element is present.

    
13.12.2018 / 14:52
1

Here is a "more elegant" solution as suggested by @Giuliana Bezerra.

$("button").click(function() {
$('#selectEmpresa').change(function(){
  $('#msg').html('');
});

var vIdEmpresa = $('#selectEmpresa option:selected').val();
var vEmpresa = $('#selectEmpresa option:selected').text();
var mensagem = $('#msg');
var linha = '<tr class="selected" id="linha' + vIdEmpresa + '">' +
      '<td>' +
      '<input class="idemp" type="hidden" name="idempresa' + vIdEmpresa + '" value="' + vIdEmpresa + '">' + vEmpresa +
      '</td>' +
      ' </tr>'  
 
if($("tr#linha" + vIdEmpresa).length === 0) {
  $('#mytbody').append(linha); 
} else {
  $('#msg').html("<b class='text-danger'>&#9888; Empresa " + vIdEmpresa + " já foi adicionada!</b>"); 
} 
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><divclass="container">
  <div class="row">

    <div class="col-md-10">
      <select class="form-control" id="selectEmpresa">
        <option value="01">Empresa 01</option>
        <option value="02">Empresa 02</option>
        <option value="03">Empresa 03</option>
      </select>
    </div>

    <div class="col-md-2">
      <button type="button" name="button">Adicionar</button>
    </div>

    <div class="col-md-12">
      <span id="msg"></span><br>
    </div>

    <div class="col-md-12">
      <table class="table table-striped">
        <thead>
          <tr>
            <th>Empresa</th>
          </tr>
        </thead>
        <tbody id="mytbody">

        </tbody>
      </table>
    </div>
  </div>
</div>
    
13.12.2018 / 21:42