Get names of all fields with the required tag

0

I want to get the name of all fields with the tag required and test one by one, if one of them is empty, I enter the name in an array. This question resembles some things with this old question mine, but the context is different.

function myFunction() {
  var inputs = [];

  jQuery('input[required]:visible,select[required]:visible').each(function() {
    jQuery(this).removeClass('erro');
    if (jQuery(this)[0].value == "" || jQuery(this)[0].value == undefined || jQuery(this).prop('checked') == false) {
      jQuery(this).addClass('erro');
      inputs.push(jQuery(this)[0].name);
    }
  });
  console.log(inputs);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="radio" name="option" value="1" required/>
<input type="radio" name="option" value="2" required />
<input type="radio" name="teste" value="3" required />
<input type="radio" name="option" value="4" required />
<input type="radio" name="option" value="5" required style="display:none">
<input type="radio" name="option" value="6" required disabled>
<input type="text" name="teste1" required>
<input type="text" name="teste2" required>
<select name="teste5" required>
  <option></option>
  <option val="1">a</option>
  <option val="2">b</option>
  <option val="3">c</option>
</select>
<input type="teste" name="teste6" required>
<button onclick="myFunction()">Click me</button>

I tried something like: jQuery(this)[0].checked=="" but it did not work very well

    
asked by anonymous 10.10.2016 / 20:09

1 answer

2

I do not know if I understood very well, but would that be what you are looking for?

function myFunction() {
  var inputs = [];

  jQuery('[required]').each(function() {
    //console.log(this);
    jQuery(this).removeClass('erro');
    if (!jQuery(this).val()) {
      console.log("entrou");
      jQuery(this).addClass('erro');
      inputs.push(jQuery(this).attr('name'));
    }
  });
  console.log(inputs);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputid="visa" type="radio" name="option" value="visa" required/>
<input id="visa" type="radio" name="option" value="visa" required />
<input id="visa" type="radio" name="teste" value="visa" required />
<input id="visa" type="radio" name="option" value="visa" required />
<input id="visa" type="radio" name="option" value="visa" required style="display:none">
<input id="visa" type="radio" name="option" value="visa" required disabled>
<input type="teste" name="teste1" required>
<input type="teste" name="teste2" required>
<select name="teste5" required>
  <option></option>
  <option val="1">a</option>
  <option val="2">b</option>
  <option val="3">c</option>
</select>
<input type="teste" name="teste6" required>

<button onclick="myFunction()">Click me</button>
    
10.10.2016 / 20:36