最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - jquery, alert when trying to submit empty field in form - Stack Overflow

matteradmin3PV0评论

I'm sure I must have missed something really obvious, but can't for the life of me see what it is.

I have the below javascript, that (in theory) looks at the form when I click submit, and tells me if I have left the 'RefNo' field blank (in the final form there will be various fields to check, so I have used class='required' to identify them all). But so far, when I click submit, nothing happens (except the form is submitted with the missing data).

I've tried various options that I have found on the internet, and this seemed the most promising.

If anyone can see what I have done wrong it would be really appreciated.

<html>
<head>
    <script language="JavaScript" src="jquery.js" type="text/javascript"></script>
    <script type="text/javascript">
        function submitForm()
        {
            $("#Form1").submit(function()
                {
                    $('.required input').each(function() 
                        {
                            if ($(this).val() == '') 
                                {   
                                    $(this).addClass('highlight');
                                }
                        }
                    );

                    if ($('.required input').hasClass('highlight')) 
                        {
                            alert("Please fill in a Ref Number and try again");
                            return false;
                        }
                }   
            );
        }
    </script>
</head>
<body>

    <form method="POST" action="test9.php" name="Form1" ID="Form1">
        <input TYPE="text" ID="RefNo" NAME="RefNo" VALUE="" size="25px" class="required"></input>

        </br>

        <p>
            <input type="submit" Name="submit" id="submitButton" value="Report History" onClick='submitForm()'></input>
        </p>
    </form> 
</body>

I'm sure I must have missed something really obvious, but can't for the life of me see what it is.

I have the below javascript, that (in theory) looks at the form when I click submit, and tells me if I have left the 'RefNo' field blank (in the final form there will be various fields to check, so I have used class='required' to identify them all). But so far, when I click submit, nothing happens (except the form is submitted with the missing data).

I've tried various options that I have found on the internet, and this seemed the most promising.

If anyone can see what I have done wrong it would be really appreciated.

<html>
<head>
    <script language="JavaScript" src="jquery.js" type="text/javascript"></script>
    <script type="text/javascript">
        function submitForm()
        {
            $("#Form1").submit(function()
                {
                    $('.required input').each(function() 
                        {
                            if ($(this).val() == '') 
                                {   
                                    $(this).addClass('highlight');
                                }
                        }
                    );

                    if ($('.required input').hasClass('highlight')) 
                        {
                            alert("Please fill in a Ref Number and try again");
                            return false;
                        }
                }   
            );
        }
    </script>
</head>
<body>

    <form method="POST" action="test9.php" name="Form1" ID="Form1">
        <input TYPE="text" ID="RefNo" NAME="RefNo" VALUE="" size="25px" class="required"></input>

        </br>

        <p>
            <input type="submit" Name="submit" id="submitButton" value="Report History" onClick='submitForm()'></input>
        </p>
    </form> 
</body>

Share Improve this question asked May 24, 2013 at 15:39 IGGtIGGt 2,78910 gold badges45 silver badges67 bronze badges 9
  • 1 html5 has a required attribute that will make using javascript irrelevant. – nathan hayfield Commented May 24, 2013 at 15:41
  • 3 But you still need to know how to do it without that attribute for people who aren't using an HTML5 pliant browser. – krillgar Commented May 24, 2013 at 15:42
  • 1 @nathanhayfield No it will not, what about browsers that don't accept html5, and don't say "Well people shouldn't be using them browsers" it's users choice. You have to have a fallback for everyone. – user2406160 Commented May 24, 2013 at 15:42
  • 2 Yes you do, otherwise it is inaccessible for users. Major panies like BBC and most government run businesses use IE7, seriously you need to go back and learn the basics. – user2406160 Commented May 24, 2013 at 15:47
  • 1 Actually users don't always have a choice on what browser they use because of work/school rules and they may only have an older browser that does not support html5 – Joe W Commented May 24, 2013 at 15:47
 |  Show 4 more ments

5 Answers 5

Reset to default 6

Your selectors should be $('input.required'), not $('.required input').

First, I think you should use Jquery validation plugin.

Ohterwise, this code should work :

-add a onsubmit="return submitForm()" in your Form tag

<form method="POST" action="test9.php" name="Form1" ID="Form1" onsubmit="return submitForm();">

-get rid of the onclick on the submit button

-and here is the submitForm function :

function submitForm() {
var valid = true;

$('input[class="required"]').each(function() {
    if ($(this).val() === '') {   
        alert("One field is empty and try again");
        valid = false;
    }
});

return valid;

}

But I really remend jquery.validate.js

Your selector appears to be a bit off:

It should be $('.required')

The way you have it tries to select an input nested inside a Required class.

Instead of doing it on form submit, remove the submit input type from the button and just have it be a regular button.

With that in mind, your javascript should be:

<script>
    $('#submitButton').click(function () {
        $('input.required').each(function() {
            if ($(this).val() == '') {   
                $(this).addClass('highlight');
            }
        });

        if ($('.highlight').length > 0) {
            alert("Please fill in a Ref Number and try again");
            return false;
        }
        else {
            $('#Form1').submit();
        }
    });
</script>

Otherwise, the way that you're doing it, you would have to cancel the event until you run your check for missing data, and then submit the form anyway. This way keeps you from having to cancel the action, as older IE browsers do that differently than the other browsers, and even newer versions of IE. So it makes your code more readable.

The selector should be either $('input.required') or $('#RefNo').

$('#RefNo') is more faster since it uses native getElementById method.

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far