3

Estou com um problema em ao preencher um campo dentro de uma tabela que está dentro de um loop For, e um dos títulos desta tabela é um botão modal, que a medida que é clicado abre uma seleção de unidades de medida. E ao usuário selecionar a unidade, o campo input é preenchido, porém como defini um array ele preenche a tabela toda. Como na foto a seguir. Tem alguma forma de preencher somente o input selecionado, ou, apenas dar um focusem um único invés de todos ?

inserir a descrição da imagem aqui

<script type="text/javascript">
$(function(){
   var prevFocus; //Escopo global

   //Ao selecionar a unidade de medida o último input focado será preenchido!
   $("#unidadeMedida").on("change", function(){
      if (typeof prevFocus  !== "undefined") {
         prevFocus.val($(this).val());
      }
   });

   $(".inputTabela").focus(function() {
      prevFocus = $(this);
   });
});
</script>

<div class="modal fade" id="myModaler" role="dialog">
    <div class="modal-dialog">
        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <label class="modal-title">Cadastro de Unidades de Medida</label>
            </div>
            <div class="modal-body">
                <table class="display example" cellspacing="0" width="100%">
                    <thead>
                        <tr>
                            <th>  Unidade </th>
                            <th>  Descrição </th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php
                        include ("conn.php");

                        $result = "SELECT * FROM cadunid ORDER BY descricao";
                        $resultado = mysqli_query($conn, $result);

                        while($row = mysqli_fetch_assoc($resultado)) {
                            echo "<tr class='btn-default id='unidadeMedida'>";
                                echo "<td class='get-value'>". $row['codigo'] ."</td>";
                                echo "<td class='get-value-codigo'>". $row['descricao'] ."</td>";
                            echo "</tr>";
                        }                      
                    ?>
                    </tbody>
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
            </div>
        </div>
    </div>
</div>
<table class="table table-striped table-bordered table-hover">
    <thead>
        <tr>
          <th>
            <button type="button" id='unidadeMedida' class="" data-toggle="modal" data-target="#myModaler">Unidade >></button>
          </th>
          <th>Preço Custo</th>
          <th>Preço Venda</th>
          <th>Peso Bruto</th>
          <th>Peso Liquido</th>
          <th>Qtd. Emb.</th>
        </tr>
    </thead>
    <tbody id='prprod'><!-- Início do Corpo da tabela / Quantidade de linhas e colunas -->
        <?php for($i = 0; $i <= 5; $i++){ // loop para criar 5 linhas na tabela ?>        
        <tr>                                                   
            <input type="hidden" maxlength="6"  name="recnum[]" style="border:none; width:100%; background-color: transparent;">
            <td><input type='text' class='inputTabela' name="unidad[]" style="border:none; width:100%; background-color: transparent;">                                                               
            <td><input type="text" class='' maxlength=""  name="preco_custo[]" placeholder="" style="border:none; width:100%; background-color: transparent;"></td>
            <td><input type="text" class='' maxlength=""  name="preco_venda[]" placeholder="" style="border:none; width:100%; background-color: transparent;"></td>
            <td><input type="text" class='' maxlength=""  name="peso_bruto[]" placeholder="" style="border:none; width:100%; background-color: transparent;"></td>
            <td><input type="text" class='' maxlength=""  name="peso_liquido[]" placeholder="" style="border:none; width:100%; background-color: transparent;"></td>
            <td><input type="text" class='' maxlength=""  name="qtde_embalagem[]" placeholder="" style="border:none; width:100%; background-color: transparent;"></td>
        </tr>
           <?php } ?>
    </tbody><!-- Fim do Corpo da tabela / Quantidade de linhas e colunas -->
</table>
3
  • então, eu fiz um teste aqui no stackoverflow, e se coloco a tag script e o Js dentro ele não roda mesmo
    – Victor
    28/11/2017 às 13:06
  • Então o simulador do stackoverflow já faz algumas coisas parar facilitar na hora de respondermos, mas você precisará rever alguns conceitos de aplicações web, pricipalmente para conseguir debuggar e identificar o erro. 28/11/2017 às 13:09
  • já não sei o que faço, porque não entendo como não funciona de jeito algum, e nem este seu exemplo ajudou, nunca passei por isso kk
    – Victor
    28/11/2017 às 13:12

1 Resposta 1

1

Pelo que entendi você deseja manipular o último elemente focado antes de clicar no botão de modal.

Para fazer isso eu adicionei uma classe a todos os input que desejo observar, toda vez que um desses input for focado eu armazeno a refêrencia do elemento na variavel prevFocus, assim sempre que a unidade de medida for alterada o último input focado receberá seu o valor selecionado, veja o exemplo abaixo:

var prevFocus; //Escopo global


//Ao selecionar a unidade de medida o último input focado será preenchido!
$("#unidadeMedida").on("change", function(){
  if (typeof prevFocus  !== "undefined") {
     prevFocus.val($(this).val());
  }
});

$(".inputTabela").focus(function() {
    prevFocus = $(this);
});
table tr td {
  border: solid 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<table class="table table-striped table-bordered table-hover">
  <thead>
    <tr>
      <th>
        <button type="button" id="modalUnidade" class="" data-toggle="modal" data-target="#myModal">Unidade >></button>
      </th>
      <th>Preço Custo</th>
      <th>Preço Venda</th>
      <th>Peso Bruto</th>
      <th>Peso Liquido</th>
      <th>Qtd. Emb.</th>
    </tr>
  </thead>
  <tbody id='prprod'>
    <tr>              
      <td>
        <input type="hidden" maxlength="6"  name="recnum[]" style="border:none; width:100%; background-color: transparent;">

        <input type='text' class="inputTabela" name="unidad[]" class="unidade-input" style="border:none; width:100%; background-color: transparent;">       </td>
      <td><input type="text" class="inputTabela" maxlength=""  name="preco_custo[]" placeholder="" style="border:none; width:100%; background-color: transparent;">
      </td>
      <td><input type="text" class="inputTabela" maxlength=""  name="preco_venda[]" placeholder="" style="border:none; width:100%; background-color: transparent;">
      </td>
      <td><input type="text" class="inputTabela" maxlength=""  name="peso_bruto[]" placeholder="" style="border:none; width:100%; background-color: transparent;">
      </td>
      <td><input type="text" class="inputTabela" maxlength=""  name="peso_liquido[]" placeholder="" style="border:none; width:100%; background-color: transparent;">
      </td>
      <td><input type="text" class="inputTabela" maxlength=""  name="qtde_embalagem[]" placeholder="" style="border:none; width:100%; background-color: transparent;">
      </td>
    </tr>
    <tr>              
      <td>
        <input type="hidden" maxlength="6"  name="recnum[]" style="border:none; width:100%; background-color: transparent;">

        <input type='text' class="inputTabela" name="unidad[]" class="unidade-input" style="border:none; width:100%; background-color: transparent;">       </td>
      <td><input type="text" class="inputTabela" maxlength=""  name="preco_custo[]" placeholder="" style="border:none; width:100%; background-color: transparent;">
      </td>
      <td><input type="text" class="inputTabela" maxlength=""  name="preco_venda[]" placeholder="" style="border:none; width:100%; background-color: transparent;">
      </td>
      <td><input type="text" class="inputTabela" maxlength=""  name="peso_bruto[]" placeholder="" style="border:none; width:100%; background-color: transparent;">
      </td>
      <td><input type="text" class="inputTabela" maxlength=""  name="peso_liquido[]" placeholder="" style="border:none; width:100%; background-color: transparent;">
      </td>
      <td><input type="text" class="inputTabela" maxlength=""  name="qtde_embalagem[]" placeholder="" style="border:none; width:100%; background-color: transparent;">
      </td>
    </tr>
  </tbody>
</table>

<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Unidades de medida</h4>
      </div>
      <div class="modal-body">
        <select id="unidadeMedida">
          <option value="">Selecione</option>
          <option value="cm">Centímetros</option>
          <option value="m">Metros</option>
        </select>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal" id="fecharModal">Close</button>
      </div>
    </div>

  </div>
</div>

1
  • 1
    agora depois de alterar para function funcionou mas só no seu exemplo, tenho que verificar como alterar meu while para obter o id='unidadeMedida' mas já dei um grande salto, obrigado
    – Victor
    28/11/2017 às 13:25

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .