How to get the value of inputs by declaring this of an element [jQuery]?

Asked

Viewed 2,558 times

1

jQuery(function($){

    $('#upusuario').on('submit', function(){

        formulario  = $(this).serialize();

Question: How I would pick up input senha and confirmasenha of this form to compare them, of course without using anything of the type var senha = $("#upusuario input[name=senha]") whereas I have already recovered the fields with serialize?

<input type="text" name="senha" class="form-control bott" required>
<input type="text" name="confirmasenha" class="form-control bott" required>

2 answers

4


No need to use .serialize(). You can access directly from this, in the case of forms HTMLFormElement.

Fields can be accessed in 3 ways:

  • on the property name country: this.nome_do_campo
  • through property .elements by index: this.elements[0]
  • through property .elements by name: this.elements['nome_do_campo']

To access the value, just use one of the above options to select the field and then the property .value to access the value:

$(function(){
  $('#upusuario').on('submit', function(e) {
    var resultado = $('#resultado');
    var senha1 = this.senha.value;
    var senha2 = this.confirmasenha.value;
    e.preventDefault(); // impede envio do formulário
    resultado.text(senha1 + ' ' + senha2);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="upusuario">
  <input type="text" name="senha" value="senha1" required/>
  <input type="text" name="confirmasenha" value="senha2" required/>
  <input type="submit"/>
</form>
<pre id="resultado"></pre>

  • +1 for not having created a elemento [jQuery] just to take the value of an input.

1

You can do through the function split(); once the function serialize(); returns a String delimited &.

See the example below:

$(document).ready(function(){
  $('button').click(function(){
    var arr = $('form').serialize().replace(/password[1,2]=/g,'').split('&');
    if(arr[0] !== arr[1]) {
      $('div').text('Senha incorreta!');
    } else {
      $('div').text('Senha correta!');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
  Password1: <input type="text" name="password1"><br>
  Password2: <input type="text" name="password2"><br>
</form>

<button>Serialize!</button>

<div></div>

Browser other questions tagged

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