How to update the Index of a field using Javascript in Asp.net MVC

Asked

Viewed 33 times

0

I’m creating fields dynamically based on a List. When I remove a field, I need to reorder them using javascript, but I am facing problems, because all fields are reordered Indexes, except those that use Razor "Asp-validation-for"... Could I give a Find and change his Index too?

Razor:

<div class="col-md-2">
    <label asp-for="PessoaFisicaViewModel.PessoasFisicasDocumentosViewModel[i].Documento" class="control-label txt-documento">Documento</label>
    <input type="text" asp-for="PessoaFisicaViewModel.PessoasFisicasDocumentosViewModel[i].Documento" class="form-control txt-documento" />
    <span asp-validation-for="PessoaFisicaViewModel.PessoasFisicasDocumentosViewModel[i].Documento" class="text-danger txt-documento"></span>
</div>

Javascript:

$(this).parent().parent().remove();
qtdDocumentos--;
$("#div-documentos .row").each(function (indice, elemento) {
    $(elemento).find(".txt-documento").attr("name", "PessoaFisicaViewModel.PessoasFisicasDocumentosViewModel[" + indice + "].Documento");
});

inserir a descrição da imagem aqui

1 answer

0


I thought I’d get all the elements validation of the page and for each change the name of them according to the index.

This way if you have other validation fields on the screen you will have to optimize the search of the components picking directly from some div.

Maybe this will help you or at least give you a north to follow friend:

  function ReordenarValidation()
  {
    var elements = document.getElementsByClassName('text-danger');

    var i;
    for (i = 0; i < elements.length; i++) {
      elements[i].attr("name", "PessoaFisicaViewModel.PessoasFisicasDocumentosViewModel["+ i +"].Documento");
    }
  }

  • Thank you @Victor Laio :)

Browser other questions tagged

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