Validate javascript line

Asked

Viewed 123 times

1

People I am trying to do a validation line by line on a table as follows: If the product is marked as yes on a supplier it cannot be marked to another supplier. Can someone please help me? Follow the model...

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

  var vIdProduto = $('#selectProduto option:selected').val();
  var vProduto = $('#selectProduto option:selected').text();
  var mensagem = $('#msg');
  var linha = '<tr class="selected" id="linha' + vIdProduto + '">' +
        '<td>' +
        '<input class="idprod" type="hidden" name="idproduto' + vIdProduto + '" value="' + vIdProduto + '">' + vProduto +
        '</td>' +
        '<td>' +
        `<select class="form-control" id="autoriza">
          <option value="">Comprar</option>
          <option value="Sim">Sim</option>
          <option value="Não">Não</option>
        </select>`+
        '</td>' +
        '<td>' +
        `<select class="form-control" id="autoriza">
          <option value="">Comprar</option>
          <option value="Sim">Sim</option>
          <option value="Não">Não</option>
        </select>`+
        '</td>' +
        '<td>' +
        `<select class="form-control" id="autoriza">
          <option value="">Comprar</option>
          <option value="Sim">Sim</option>
          <option value="Não">Não</option>
        </select>`+
        '</td>' +
        ' </tr>'

  if($("tr#linha" + vIdProduto).length === 0) {
    $('#mytbody').append(linha);
  } else {
    $('#msg').html("<b class='text-danger'>&#9888; Produto " + vIdProduto + " já foi adicionado!</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="selectProduto">
        <option value="A">Produto A</option>
        <option value="B">Produto B</option>
        <option value="C">Produto C</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>Produto</th>
            <th>Forn01</th>
            <th>Forn02</th>
            <th>Forn03</th>
          </tr>
        </thead>
        <tbody id="mytbody">

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

  • 1

    Could you explain your problem better? I’m confused in your question rsrs.

  • Thanks for the feedback, I can. I can’t let the system accept that the user buys the same product from different suppliers, right? Ex: If it scores yes in select forn01 select forn02 and forn03 will have to be no or desbilitar understood?

  • 2

    Guy your code is liable to generate problems, are repeating the ids of selects servants.

  • Thanks for the return Leandrade , I will correct.

3 answers

2

The sensible thing for such a form would be to use input type radio

When an option RADIO is checked, this will only be unchecked when another option RADIO with the same name is selected.

See how it works

Produto A <input type="radio" name="prodA" value="Forn01"/>
<input type="radio" name="prodA" value="Forn02"/>
<input type="radio" name="prodA" value="Forn03"/>
<br>
Produto B <input type="radio" name="prodB" value="Forn01"/>
<input type="radio" name="prodB" value="Forn02"/>
<input type="radio" name="prodB" value="Forn03"/>
<br>
Produto C <input type="radio" name="prodC" value="Forn01"/>
<input type="radio" name="prodC" value="Forn02"/>
<input type="radio" name="prodC" value="Forn03"/>

So your code would work like this: see this form being recovered in PHP

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

  var vIdProduto = $('#selectProduto option:selected').val();
  var vProduto = $('#selectProduto option:selected').text();
  var mensagem = $('#msg');
  var linha = '<tr class="selected" id="linha' + vIdProduto + '">' +
        '<td>' +
        '<input class="idprod" type="hidden" name="idproduto' + vIdProduto + '" value="' + vIdProduto + '">' + vProduto +
        '</td>' + 
        '<td>' + 
        '<input type="radio" name="prod'+vIdProduto +'" value="Forn01">'+
        '</td>' +
        '<td>' + 
        '<input type="radio" name="prod'+vIdProduto +'" value="Forn02">'+
        '</td>' +
        '<td>' +
        '<input type="radio" name="prod'+vIdProduto +'" value="Forn03">'+
        '</td>' +
        ' </tr>'

  if($("tr#linha" + vIdProduto).length === 0) {
    $('#mytbody').append(linha);
  } else {
    $('#msg').html("<b class='text-danger'>&#9888; Produto " + vIdProduto + " já foi adicionado!</b>");
  }
});
<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="selectProduto">
        <option value="A">Produto A</option>
        <option value="B">Produto B</option>
        <option value="C">Produto C</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">
    <form action="" method="post">
      <table class="table table-striped">
        <thead>
          <tr>
            <th>Produto</th>
            <th>Forn01</th>
            <th>Forn02</th>
            <th>Forn03</th>
          </tr>
        </thead>
        
        <tbody id="mytbody">

        </tbody>

      </table>
              <input type="submit">
        </form>
    </div>
  </div>
</div>

  • That’s right. It looks much better.

  • Thanks for the feedback, Sam and Leo. I tried to do so but I have to use the input name as the error name[] dai at the time of recovering the data in php.

  • @frodrigues, as well usar o name do input como name[] ? And what input you refer to?

  • I’m using php with Laravel. In the controllher when I receive the requests to put inside the loop to insert into the database it gives me a non-quotable object message if I do not put the name with keys in front.

  • Ex: $cont = 0; while($cont < Count($idproduct)){&#xA; $detalhe = new RequisicaoDet();&#xA; $detalhe->idrequisicao=$requisicoes->idrequisicao;&#xA; $detalhe->idproduto=$idproduto[$cont];&#xA; $detalhe->qnt=$qnt[$cont];&#xA; $detalhe->detalhe=$detalhes[$cont];&#xA; $detalhe->idcentrocusto=$idcentrocusto[$cont]; $detail->save(); $cont=$cont+1; }

  • I mean the product input ok.

  • @frodrigues, blz, de Laravel understand chongas :)

  • Kkkk. Vlw already helped a lot.

Show 3 more comments

0

First we will remove the id="autoriza" of their select, because they’re duplicated and that’s a problem.

Now we will add a new class to your select so we can recognize them in Javascript. Put all the same code below:

<select class="form-control select-comprar">

Finally, add Javascript to handle enabling and disabling selects:

$('.select-comprar').on('change', function () {
    if ($(this).val() == "Sim") {
        controlarHabilitacaoSelectComprar(false, $(this));
    }
    else {
        controlarHabilitacaoSelectComprar(true, $(this));
    }
});

function controlarHabilitacaoSelectComprar(habilitar, coluna) {
    //Pegamos todas as colunas da mesma linha do select que alteramos o valor
    var siblings = coluna.parent().siblings();

    //Iremos realizar um loop em todos os selects que possuirem a classe que definimos como "select-comprar"
    siblings.find('.teste-select').each(function () {
        if (habilitar) {
            $(this).removeAttr('disabled');
        }
        else {
            $(this).attr('disabled', 'disabled');
            $(this).val('Não');
        }
    });
}
  • Thanks Peter very good

0


As already said, repeating id’s is incorrect and brings problems. In fact you won’t even need id’s in the selects, so remove them all.

Just create this event that will disable the other selects of the same line when selecting one of the options:

$(document).on("change", "#mytbody select", function(){

   if($(this).val() == "Sim"){
      $(this).closest("tr").find("select").not(this).prop("disabled", true);
   }else{
      $(this).closest("tr").find("select").prop("disabled", false);
   }

});

If you select the "Buy" option again (which has an empty value), the other options are enabled again.

I didn’t understand the "No" option function. It wouldn’t be enough just the "Yes" option and what was not marked "Yes" leave empty in the option "Buy"?

Behold:

$(document).on("change", "#mytbody select", function(){
   
   if($(this).val() == "Sim"){
      $(this).closest("tr").find("select").not(this).prop("disabled", true);
   }else{
      $(this).closest("tr").find("select").prop("disabled", false);
   }
   
});

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

  var vIdProduto = $('#selectProduto option:selected').val();
  var vProduto = $('#selectProduto option:selected').text();
  var mensagem = $('#msg');
  var linha = '<tr class="selected" id="linha' + vIdProduto + '">' +
        '<td>' +
        '<input class="idprod" type="hidden" name="idproduto' + vIdProduto + '" value="' + vIdProduto + '">' + vProduto +
        '</td>' +
        '<td>' +
        `<select class="form-control">
          <option value="">Comprar</option>
          <option value="Sim">Sim</option>
          <option value="Não">Não</option>
        </select>`+
        '</td>' +
        '<td>' +
        `<select class="form-control">
          <option value="">Comprar</option>
          <option value="Sim">Sim</option>
          <option value="Não">Não</option>
        </select>`+
        '</td>' +
        '<td>' +
        `<select class="form-control">
          <option value="">Comprar</option>
          <option value="Sim">Sim</option>
          <option value="Não">Não</option>
        </select>`+
        '</td>' +
        ' </tr>'

  if($("tr#linha" + vIdProduto).length === 0) {
    $('#mytbody').append(linha);
  } else {
    $('#msg').html("<b class='text-danger'>&#9888; Produto " + vIdProduto + " já foi adicionado!</b>");
  }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">

<div class="container">
  <div class="row">

    <div class="col-md-10">
      <select class="form-control" id="selectProduto">
        <option value="A">Produto A</option>
        <option value="B">Produto B</option>
        <option value="C">Produto C</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>Produto</th>
            <th>Forn01</th>
            <th>Forn02</th>
            <th>Forn03</th>
          </tr>
        </thead>
        <tbody id="mytbody">

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

  • I can’t repent and change supplier?

  • This is half-way, you have to explain to the user this scheme

  • not that, I say on the page have to instruct the user type `friend if you want to change supplier select the option "Buy" (which has empty value) and choose another furnace

  • It would even be valid, but as I found the option "No" unnecessary, nor was I wasting time with it.

  • Actually, this should be a radiobutton.

  • Now you’ve come where I wanted

  • Thanks Sasm, excellent example, I will implement. I wavered in the same ids. Ref to Nao doesn’t really make sense. Regarding the radio I am having difficulty at the time of receiving this in php because I have to use it with (name[]) dai an error to insert in the database.

Show 2 more comments

Browser other questions tagged

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