[javascript] 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"/>

This question is related to javascript jquery

The answer is


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

});

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

It will only return inputs which have required attribute.


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

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.