JS or Jquery pass two array’s, input text and input check when checked

Asked

Viewed 43 times

0

I need to pick up the text field when the input check is checked. I can already pick up my controller. But the text field is not. They are generated by the database and therefore need to be treated as an array, because the number and description of the groups always vary according to the part.

inserir a descrição da imagem aqui

Below I show how these fields are generated:

      function CarregaGrupo() {
            $.ajax({
                url: "/RTRC_Solucao/CarregaSelectGrupo",
                data: {
                    IdRTRC: $("#Id_Rtrc").val()
                },
                async: false,
                success: function (data) {
                    $("#checkboxesGrupo").empty();

                    $.each(data, function (i, element) {                    
                        if (element.TemGrupo > 0) {
                            $('#checkboxesGrupo').append('<input type="text" name="optionsObsGrupo[]" />  <input type="checkbox" name="optionsGrupo[]" value=' + element.Id + ' checked /> ' + element.Descricao + '<br />');

                        } else {

                            $('#checkboxesGrupo').append('<input type="text" name="optionsObsGrupo[]" />  <input type="checkbox" name="optionsGrupo[]" value=' + element.Id + ' /> ' + element.Descricao + ' <br />');
                        }

                    });

                }
            });
        }

Below I show how I get the input check:

 $("#AdicionarGrupoPeca").click(function () {

        var checkedsGrupo = [];
        var obsGrupo = [];


        $("input[name='optionsGrupo[]']:checked").each(function () {
            checkedsGrupo.push($(this).val());
            obsGrupo.push($("input[type=text][name='optionsObsGrupo']").val());          
        });  


        jQuery.ajax({
            type: "POST",
            url: "/RTRC_Solucao/AdicionarGrupoPeca",
            dataType: "json",
            data: {
                checkedsGrupo: checkedsGrupo,  
                obsGrupo: obsGrupo,                    
                IdRTRC: $("#Id_Rtrc").val(),
                ObservacaoReposicao: $("#ObservacaoReposicao").val()
            },
            success: function (data) {
                $("#respostaPecaProduto").addClass("alert alert-success");
                $('#respostaPecaProduto').html('Salvo com sucesso');
                $('#respostaPecaProduto').show();
                setTimeout(function () {
                    $('#respostaPecaProduto').fadeOut('fast');
                }, 1000);
            },
            error: function (request, status, erro) {
                $("#respostaPecaProduto").addClass("alert alert-danger");
                $('#respostaPecaProduto').html('Contato NÃO FOI REMOVIDO!', erro);
                $('#respostaPecaProduto').show();
                setTimeout(function () {
                    $('#respostaPecaProduto').fadeOut('fast');
                }, 1000);
            },
            complete: function (jqXHR, textStatus) {
                CarregaPecas();
                $('#ModalPeca').modal('hide');
            }
        });

    });

Asp.Net gets the marked ones right, however it arrives null or "" the Obs fields (input text)

  [HttpPost]
        public JsonResult AdicionarGrupoPeca(int[] checkedsGrupo,string[] obsGrupo, int IdRTRC, string ObservacaoReposicao)
        {

            Dao.AdicionarGrupoPeca(checkedsGrupo, obsGrupo, checkedsPeca, obsPeca, IdRTRC, ObservacaoReposicao);
            return Json("Dados salvo com sucesso!!");
        }




HTML

<div class="modal fade in" id="ModalPeca" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">×</span>
                            </button>
                            <h4 class="modal-title">Adicionar Peça de Reposição</h4>
                        </div>
                        <div class="modal-body">
                            <div class="form-group">
                                <label class="col-sm-2 control-label">GRUPO:</label>
                                <div class="col-sm-10">
                                    @*<select id="Peca_Produto" class="form-control"></select>*@
                                    <div id="checkboxesGrupo">
                                        <!-- AQUI VEM OS CHECKS DAS PEÇAS-->
                                    </div>
                                </div>
                            </div>
                            <br /><br /><br /><br />
                            <hr />


                            <div class="form-group">
                                <br /><br /><br /><br />
                                <br /><br /><br />
                                <hr />
                                <label class="col-sm-2 control-label">Observação:</label>
                                <div class="col-sm-10">
                                    <textarea id="ObservacaoReposicao" class="form-control"></textarea>
                                </div>
                            </div>
                            <br /><br /><br /><br />
                            <div id="respostaPecaProduto"></div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-primary" id="AdicionarGrupoPeca">Atualizar Peça</button>
                                <button type="button" id="fecharModal" class="btn btn-primary">Fechar</button>
                            </div>
                        </div>

                    </div>

                </div>
                <!-- /.modal-content -->
            </div>
            <!-- /.modal-dialog --> 
  • if you have several input text as well as checkboxes, you should use a each to get the values of all, just like you did with the checkbox, that is, a selector ocm each for the checkbox and another for input text

  • @Ricardopunctual the problem you need only picks up when Check is checked so that the index is equal. Type che[1] = Obs[1] . What does not occur if the check is not scheduled, it continues to catch the Obs.

  • then you need to use the this as a reference to get the next inputs. You can ask the question an example of html with the structure you have inside the "group" to better understand and help suggest a selector that helps

  • I put the HTML

1 answer

1


Let’s go by parts, the selector can be made like this:

$(this).prev("input:text[name='optionsObsGrupo[]']")

  • used the this to use the checkbox as reference;
  • prev to get the nearest element before checkbox
  • input:text we want the text input
  • name='optionsObsGrupo[]' here is the name, and in its code the conchetes were missing

Here a working example:

$("#AdicionarGrupoPeca").click(function () {

        var checkedsGrupo = [];
        var obsGrupo = [];


        $("input[name='optionsGrupo[]']:checked").each(function () {
            checkedsGrupo.push($(this).val());
            obsGrupo.push($(this).prev("input:text[name='optionsObsGrupo[]']").val());
        });  
        
        alert(obsGrupo);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="checkboxesGrupo">
  
  <input type="text" name="optionsObsGrupo[]" value="T1" />  
  <input type="checkbox" name="optionsGrupo[]"  /> 
  <br />
  
  <input type="text" name="optionsObsGrupo[]" value="T2" />  
  <input type="checkbox" name="optionsGrupo[]"  /> 
  <br />
  
  <input type="text" name="optionsObsGrupo[]" value="T3" />  
  <input type="checkbox" name="optionsGrupo[]"  /> 
  <br />
  
</div>

<button id="AdicionarGrupoPeca">Testar</button>

Browser other questions tagged

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