48

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

2
  • What does your HTML look like? And what version jQuery are you using? Also, try $(this).is(':required'); Commented Aug 28, 2013 at 18:18
  • JQ: 1.9.1 and adding html now. Commented Aug 28, 2013 at 18:20

6 Answers 6

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

Sign up to request clarification or add additional context in comments.

2 Comments

Maybe you can also point out here, how to output a text that this input is required manually in f(!$(this).prop('required')){ block?
What about <input required="">? Is that seen as false?
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.

Comments

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

2 Comments

What's the browser support like for this?
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 */ });
4
$('form#register input[required]')

It will only return inputs which have required attribute.

Comments

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

});

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.