Tristan Cunningham
Tristan Cunningham

Reputation: 919

Checking if an input field is required using jQuery

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"/>

Upvotes: 48

Views: 150862

Answers (6)

Ayham Kamel
Ayham Kamel

Reputation: 9

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>

Upvotes: 0

ankur makavana
ankur makavana

Reputation: 21

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 );
    }

});

Upvotes: 1

Aamir Nakhwa
Aamir Nakhwa

Reputation: 391

$('form#register input[required]')

It will only return inputs which have required attribute.

Upvotes: 4

JPollock
JPollock

Reputation: 3558

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.

Upvotes: 18

Kris Selbekk
Kris Selbekk

Reputation: 7634

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 */);

Upvotes: 8

rink.attendant.6
rink.attendant.6

Reputation: 46218

The required property is boolean:

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

Reference: HTMLInputElement

Upvotes: 96

Related Questions