How do I get the value of inputs by declaring this of a [jQuery] element?

1
jQuery(function($){

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

        formulario  = $(this).serialize();

Question: How would I get the input senha and confirmasenha of this form to compare them, of course without using something like var senha = $("#upusuario input[name=senha]") since 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>
    
asked by anonymous 10.11.2015 / 00:44

2 answers

4

You do not need to use .serialize() . You can directly access from this , which in the case of forms is a HTMLFormElement .

Fields can be accessed in 3 ways:

  • via the name property of the field : this.nome_do_campo
  • through the property .elements by index: this.elements[0]
  • through the property .elements by name: this.elements['nome_do_campo']

To access the value, simply use one of the options above to select the field and then the .value property 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><formid="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>
    
10.11.2015 / 12:04
1

You can do this by means of the split(); function since the serialize(); function returns a String with & delimiter.

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:<inputtype="text" name="password1"><br>
  Password2: <input type="text" name="password2"><br>
</form>

<button>Serialize!</button>

<div></div>
    
10.11.2015 / 06:39