0

I am using HTML5's required attribute on my input elements and select boxes and PHP for validation.

How can I show an alert if the required fields are not filled in? I tried using onsubmit() but the form is processed anyway and no alert is shown.

1
  • Please show us your code, ideally in a jsFiddle. We can hardly debug code if we don't see it. Commented Apr 9, 2014 at 7:15

3 Answers 3

1

If the user's browser supports html5, he cant submit the form if not all the required fields have been written into.

Generally, you can prevent a form from submitting in jQuery like so:

$('#yourformselector').submit(function(event) {
    $(this).find('[required="required"]').each(function() {
        if (!$(this).val().length) {
            event.preventDefault();
            return false;
        }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

0

If you are using a modern/newer web browser, your default browser alerts should automatically display.

Or try:

    $(document).ready(function() {
    $('form').submit(function() {
        var incomplete = $('form :input').filter(function() {
                             return $(this).val() == '';
                         });
        //if incomplete contains any elements, the form has not been filled 
        if(incomplete.length) {
            alert('please fill out the form');
            //to prevent submission of the form
            return false;
        }
     });
});

1 Comment

i am only want to check that element which contain only 'required' attribute.
0

You may use checkValidity(), it will try to validate with attributes like pattern, min, max, required, etc. Follow this link to go deeper here

function myFunction() {
    var inpObj = document.getElementById("id1");
    if (inpObj.checkValidity() == false) {
        alert('invalid input')
    } else {
        alert('valid input')
    } 
} 
<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>

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.