Validate form with equal name[] and id

Asked

Viewed 220 times

0

I have a dynamic form, where can appear several textarea, and by default, these textarea has the same id and the same name, however, the name is being sent as array (name="nomecampo[]"). I wanted to know how to validate all these textarea in the javascript, because I need to check these textarea is less than 10 characters.

To textarea this way:

<textarea class="form-control txta" rows="4" name="descr_icon[]" id="descri_icon" ></textarea>

And since the form is dynamic, one, none, or several may appear textarea equal to this, and I need to validate in javascript (I need it to be pure, I can’t use it jquery) each textarea but the validation is the same for all.

I found some solutions counting the index of textarea for name, but in my case the name this passing as array, so it didn’t work out. What I found was something like this:

function validacao(nomecampo) {
    var total = document.getElementsByName(nomecampo);
    for(i = 0; i < total.lenght; i++) {
        if (document.getElementByName(i) < 10) {
            alert('Erro');
          return (false);
        }
    }
}

And in function call:

<textarea name="camponome" id="camponome"></textarea>
<button onclick="validacao('camponome')"></button>

But like I said, it didn’t work in my case because I pass the name as array (name = nomecampo[]).

Would anyone know any possible solution?

  • 1

    "these textarea has the same id" O id is supposed to be single on one page.

  • Why not use class instead of id since the class can be used on more than one element?

1 answer

1


The function call you have to pass exactly as it is in the name.

<button onclick="validacao('descr_icon[]')">Validar campos</button>

In the function you have to go through the elements and check each element, taking the element by the for index.

function validacao(nomeDosCampos) {
        var todosTextArea = document.getElementsByName(nomeDosCampos);
        for (var i = 0; i < todosTextArea.length; i++) {
            var textArea = todosTextArea[i];
            if (textArea.value.length < 10) {
                alert("Não é permitido menos de 10 caracteres");
                return;
            }
        }
 }
  • Had tried this way, but had not put the variable textarea = all!

Browser other questions tagged

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