[javascript] How to show validation message below each textbox using jquery?

I am trying to make a login form in which I have email address and password as the textbox. I have done the validation on the email address part so that it should have proper email address and also on the empty check both for email address and password text box.

Here is my jsfiddle.

As of now, I have added an alert box saying, Invalid if email address and password textbox is empty. Instead of that, I would like to show a simple message just below each text box saying , please enter your email address or password if they are empty?

Just like it has been done here on sitepoint blog.

Is this possible to do in my current html form?

Update:-

<body>

    <div id="login">

        <h2>
            <span class="fontawesome-lock"></span>Sign In
        </h2>

        <form action="login" method="POST">
            <fieldset>
                <p>
                    <label for="email">E-mail address</label>
                </p>
                <p>
                    <input type="email" id="email" name="email">
                </p>
                <p>
                    <label for="password">Password</label>
                </p>
                <p>
                    <input type="password" name="password" id="password">
                </p>
                <p>
                    <input type="submit" value="Sign In">
                </p>

            </fieldset>

        </form>

    </div>
    <!-- end login -->

</body>

And my js -

<script>
    $(document).ready(function() {
        $('form').on('submit', function (e) {
            e.preventDefault();

            if (!$('#email').val()) {
                if ($("#email").parent().next(".validation").length == 0) // only add if not added
                {
                    $("#email").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter email address</div>");
                }
            } else {
                $("#email").parent().next(".validation").remove(); // remove it
            }
            if (!$('#password').val()) {
                if ($("#password").parent().next(".validation").length == 0) // only add if not added
                {
                    $("#password").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter password</div>");

                }
            } else {
                $("#password").parent().next(".validation").remove(); // remove it
            }
        }); 
    });

</script>

I am working with JSP and Servlets so as soon as I click Sign In button, it was taking me to another page with valid email and password earlier but now nothing is happening after I click Sign In button with valid email and password.

Any thoughts what could be wrong?

This question is related to javascript jquery html css

The answer is


You could put static elements after the fields and show them, or you could inject the validation message dynamically. See the below example for how to inject dynamically.

This example also follows the best practice of setting focus to the blank field so user can easily correct the issue.

Note that you could easily genericize this to work with any label & field (for required fields anyway), instead of my example which specifically codes each validation.

Your fiddle is updated, see here: jsfiddle

The code:

$('form').on('submit', function (e) {
    var focusSet = false;
    if (!$('#email').val()) {
        if ($("#email").parent().next(".validation").length == 0) // only add if not added
        {
            $("#email").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter email address</div>");
        }
        e.preventDefault(); // prevent form from POST to server
        $('#email').focus();
        focusSet = true;
    } else {
        $("#email").parent().next(".validation").remove(); // remove it
    }
    if (!$('#password').val()) {
        if ($("#password").parent().next(".validation").length == 0) // only add if not added
        {
            $("#password").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter password</div>");
        }
        e.preventDefault(); // prevent form from POST to server
        if (!focusSet) {
            $("#password").focus();
        }
    } else {
        $("#password").parent().next(".validation").remove(); // remove it
    }
});  

The CSS:

    .validation
    {
      color: red;
      margin-bottom: 20px;
    }

is only the matter of finding the dom where you want to insert the the text.

DEMO jsfiddle

$().text(); 

Here you go:

JS:

$('form').on('submit', function (e) {
    e.preventDefault();

    if (!$('#email').val()) 
        $('#email').parent().append('<span class="error">Please enter your email address.</span>');


    if(!$('#password').val())
         $('#password').parent().append('<span class="error">Please enter your password.</span>');
});

CSS:

@charset "utf-8";
/* CSS Document */

/* ---------- FONTAWESOME ---------- */
/* ---------- http://fortawesome.github.com/Font-Awesome/ ---------- */
/* ---------- http://weloveiconfonts.com/ ---------- */

@import url(http://weloveiconfonts.com/api/?family=fontawesome);

/* ---------- ERIC MEYER'S RESET CSS ---------- */
/* ---------- http://meyerweb.com/eric/tools/css/reset/ ---------- */

@import url(http://meyerweb.com/eric/tools/css/reset/reset.css);

/* ---------- FONTAWESOME ---------- */

[class*="fontawesome-"]:before {
  font-family: 'FontAwesome', sans-serif;
}

/* ---------- GENERAL ---------- */

body {
    background-color: #C0C0C0;
    color: #000;
    font-family: "Varela Round", Arial, Helvetica, sans-serif;
    font-size: 16px;
    line-height: 1.5em;
}

input {
    border: none;
    font-family: inherit;
    font-size: inherit;
    font-weight: inherit;
    line-height: inherit;
    -webkit-appearance: none;
}

/* ---------- LOGIN ---------- */

#login {
    margin: 50px auto;
    width: 400px;
}

#login h2 {
    background-color: #f95252;
    -webkit-border-radius: 20px 20px 0 0;
    -moz-border-radius: 20px 20px 0 0;
    border-radius: 20px 20px 0 0;
    color: #fff;
    font-size: 28px;
    padding: 20px 26px;
}

#login h2 span[class*="fontawesome-"] {
    margin-right: 14px;
}

#login fieldset {
    background-color: #fff;
    -webkit-border-radius: 0 0 20px 20px;
    -moz-border-radius: 0 0 20px 20px;
    border-radius: 0 0 20px 20px;
    padding: 20px 26px;
}

#login fieldset div {
    color: #777;
    margin-bottom: 14px;
}

#login fieldset p:last-child {
    margin-bottom: 0;
}

#login fieldset input {
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
}

#login fieldset .error {
    display: block;
     color: #FF1000;
    font-size: 12px;
}
}

#login fieldset input[type="email"], #login fieldset input[type="password"] {
    background-color: #eee;
    color: #777;
    padding: 4px 10px;
    width: 328px;
}

#login fieldset input[type="submit"] {
    background-color: #33cc77;
    color: #fff;
    display: block;
    margin: 0 auto;
    padding: 4px 0;
    width: 100px;
}

#login fieldset input[type="submit"]:hover {
    background-color: #28ad63;
}

HTML:

<div id="login">

<h2><span class="fontawesome-lock"></span>Sign In</h2>

<form action="javascript:void(0);" method="POST">

    <fieldset>

        <div><label for="email">E-mail address</label></div>
        <div><input type="email" id="email" /></div>

        <div><label for="password">Password</label></div>
        <div><input type="password" id="password" /></div> <!-- JS because of IE support; better: placeholder="Email" -->

        <div><input type="submit" value="Sign In"></div>

    </fieldset>

</form>

And the fiddle: jsfiddle


The way I would do it is to create paragraph tags where you want your error messages with the same class and show them when the data is invalid. Here is my fiddle

if ($('#email').val() == '' || !$('#password').val() == '') {
    $('.loginError').show();
    return false;
}

I also added the paragraph tags below the email and password inputs

<p class="loginError" style="display:none;">please enter your email address or password.</p>

This is the simple solution may work for you.

Check this solution

$('form').on('submit', function (e) {
e.preventDefault();
var emailBox=$("#email");
var passBox=$("#password");
if (!emailBox.val() || !passBox.val()) {
    $(".validationText").text("Please Enter Value").show();
}
else if(!IsEmail(emailBox.val()))
{
    emailBox.prev().text("Invalid E-mail").show();
}
$("input#email, input#password").focus(function(){
    $(this).prev(".validationText").hide();
});});

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width