Insert Javascript line

Asked

Viewed 160 times

4

I’m doing a validation example for a dynamic table and would like a bug help here. When I make the first insertion he gives right, when I change, he let 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>

<div class="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>

<script src="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>

  • Use your browser developer’s console and note the error log it shows to help identify the issue.

  • thanks for the return. I am using it no error return, just duplicate everything.

  • Your doubt was not very clear.

  • I’ll try to elaborate. When adding from select to table it cannot let you enter in duplicity, it needs to bar and inform the user that it has already been inserted.

2 answers

4


The problem is the bond you make:

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

This loop is used to verify that the company has already been added by traversing all items in the table. The problem is that the append company is being done before comparing and company added to all companies in the table. You need to modify your code to do the append out of the check 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 variable was created empresaJaAdicionada to store whether the company was found in the table or not. The key point here is that the company’s addition code in the table will now run after the foreach, thus ensuring that all companies were consulted and the new company was not found, and can then 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>

<div class="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 of them is to create a business vector and manipulate it during the addition of companies, rather than checking in the DOM whether the element is present.

  • Thanks Giuliana, I realize that I faltered right there, it makes sense. ref. to vector I will research on this if you have any dirt from post search please, I would like to assemble these examples and post to anyone who has doubt. Thank you very much.

  • I really like this javascript course: https://watchandcode.com/courses/60264/lectures/896960. It teaches you how to create a TODO List with this strategy of manipulating the same data separately from the view, which would apply to your example. If you have time, I recommend.

  • Okay. I’ll access. Thanks again.

  • You need to make two small adjustments to the @Giulianabezerra script. 1-) All TR have the same ID: linha0. Correction: Define vIdEmpresa for the numbering of the ID instead of count as it is in the script. 2-) All input have the same attribute value name. Correction: Same criterion as above.

  • Thank you. Maujor. very good indeed. I will share.

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>
<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>
          </tr>
        </thead>
        <tbody id="mytbody">

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

  • ball show, learned a little more.

  • Now only to exemplify Maujor and if we add a column with select and another with checkbox and another with radio as it would be?

  • @Could frodrigues detail better what you intend?

  • Yes of course. I intend to add in the above example in addition to input, a column with select, a radio and one with checkox in each dynamic line and check each one as we did with input. I’ll post an example.

  • Now have a detail and to take the request this and save in the bank? I tested here and gave : Count(): Parameter must be an array or an Object that Implements Countable

  • @frodrigues I await details. I don’t understand what you intend to do.

  • I would just like if possible to complement the example. Checking what is marked in the checkbox, radio and select. Just for example.

Show 2 more comments

Browser other questions tagged

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