47

What would be the easiest way to check if an input is required? I have been trying stuff along these lines but always comes up with all required (only 4/6 are).

$('form#register').find('input').each(function(){
    if($(this).prop('required') == 'undefined'){
        console.log("NR");
    } else {
        console.log("IR");
    }
})

(I have tried .attr aswell)

Im trying to use it for form ajax validation, Im doing it this way at the moment:

if($('form#register span').length == $('form#register').children(".green").length){
    $('input#register-sub').prop('disabled', false);
} else {
    $('input#register-sub').prop('disabled', true);
}

Thanks.

EDIT: Html adding

<form id="register" action="" method="post" autocomplete="on">
<label>Nickname:</label><input type="text" name="name" value="<? echo $_POST['name'] ?>" required="" /><span id="reg-name"></span><br />

<?  if($user->type == "l"){ ?>
<label>email:</label><input type="email" name="email" value="<? echo $_POST['email'] ?>" required="" /><span id="reg-email"></span><br />
<label>Password:</label><input type="password" name="password" value="<? echo $_POST['password'] ?>" required="" /><span id="reg-password"></span><br />
<label>Again:</label><input type="password" name="password-test" value="<? echo $_POST['password-test'] ?>" required="" /><span id="reg-password-test"></span><br />
<label>Avatar:</label><input type="url" name="avatar" value="<? echo $_POST['avatar'] ?>" /><span id="reg-avatar"></span><br /> 
<? } ?>

<input type="submit" value="Register" disabled="" id="register-sub"/>

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
Tristan Cunningham
  • 909
  • 2
  • 10
  • 24

6 Answers6

96

The required property is boolean:

$('form#register').find('input').each(function(){
    if(!$(this).prop('required')){
        console.log("NR");
    } else {
        console.log("IR");
    }
});

Reference: HTMLInputElement

gsamaras
  • 71,951
  • 46
  • 188
  • 305
rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
18

A little bit of a more complete answer, inspired by the accepted answer:

$( '#form_id' ).submit( function( event ) {
        event.preventDefault();

        //validate fields
        var fail = false;
        var fail_log = '';
        var name;
        $( '#form_id' ).find( 'select, textarea, input' ).each(function(){
            if( ! $( this ).prop( 'required' )){

            } else {
                if ( ! $( this ).val() ) {
                    fail = true;
                    name = $( this ).attr( 'name' );
                    fail_log += name + " is required \n";
                }

            }
        });

        //submit if fail never got set to true
        if ( ! fail ) {
            //process form here.
        } else {
            alert( fail_log );
        }

});

In this case we loop all types of inputs and if they are required, we check if they have a value, and if not, a notice that they are required is added to the alert that will run.

Note that this, example assumes the form will be proceed inside the positive conditional via AJAX or similar. If you are submitting via traditional methods, move the second line, event.preventDefault(); to inside the negative conditional.

Max P.
  • 28
  • 6
JPollock
  • 3,218
  • 4
  • 26
  • 36
8

You don't need jQuery to do this. Here's an ES2015 solution:

// Get all input fields
const inputs = document.querySelectorAll('#register input');

// Get only the required ones
const requiredFields = Array.from(inputs).filter(input => input.required);

// Do your stuff with the required fields
requiredFields.forEach(field => /* do what you want */);

Or you could just use the :required selector:

Array.from(document.querySelectorAll('#register input:required'))
    .forEach(field => /* do what you want */);
Kris Selbekk
  • 7,438
  • 7
  • 46
  • 73
  • 2
    What's the browser support like for this? – GeorgeButter Dec 14 '17 at 04:18
  • 1
    `querySelector` supports IE9 and above, `Array.from` requires a polyfill for IE11 and below, and arrow functions are not supported in IE11 and below. You can either use a transpiler like Babel or just change out arrow functions for regular anonymous functions - `Array.from(...).forEach(function(field) { /* do what you want */ });` – Kris Selbekk Dec 15 '17 at 10:54
4
$('form#register input[required]')

It will only return inputs which have required attribute.

Aamir Nakhwa
  • 393
  • 1
  • 12
1

The below code works fine but I am not sure about the radio button and dropdown list

$( '#form_id' ).submit( function( event ) {
    event.preventDefault();

    //validate fields
    var fail = false;
    var fail_log = '';
    var name;
    $( '#form_id' ).find( 'select, textarea, input' ).each(function(){
        if( ! $( this ).prop( 'required' )){

        } else {
            if ( ! $( this ).val() ) {
                fail = true;
                name = $( this ).attr( 'name' );
                fail_log += name + " is required \n";
            }

        }
    });

    //submit if fail never got set to true
    if ( ! fail ) {
        //process form here.
    } else {
        alert( fail_log );
    }

});
einUsername
  • 1,569
  • 2
  • 15
  • 26
0

In response to:

What would be the easiest way to check if an input is required?

The answer is:

the power of .is()

I use it to check any attribute, e.g.: .is('[type="image"]'), .is(':disabled') or .is('[disabled]')... etc. It returns a boolean.

    
    $(':input').each(function(){
      var ID  = $(this).prop('id'),
          req = $(this).is('[required]'),
          img = $(this).is('[type="image"]');
      
      if(img){
        alert(ID + ' is an image input');
      } else {
        alert(ID + ' is NOT an image');
      }
      
      if(req){
        alert(ID + ' is required');
      } else {
        alert(ID + ' is NOT required');
      }
      

    });

        
   
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="inOne" name="test" required>
<input type="text" id="inTwo" name="test">
<input type="image" id="inThree" name="test" required>