Phi
Phi

Reputation: 335

Adding Span with Class to a input tag with Jquery

I am trying to add a Span after my Input that will have the class "error" and the text "test".

I've tried the append, and insertAfter methods. I can get the code to work on jsfiddle but I cannot get the code to work on my application.

I have put the HTML and JS/Jquery below. My end result would have a Span (with the class error) next to each input with the type text. I would then set a value for this span based on a validation loop.

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Zito - Lab 7</title>
    <link rel="stylesheet" href="main.css">
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js" type="text/javascript"></script>
    <script src="http://code.jquery.com/jquery-1.8.3.min.js" type="text/javascript"></script>
    <script src="reservation.js" type="text/javascript"></script>
</head>

<body>
    <h1>Reservation Request</h1>
    <form action="response.html" method="get"
          name="reservation_form" id="reservation_form">
        <fieldset>
            <legend>General Information</legend>
            <label for="arrival_date">Arrival date:</label>
            <input type="text" name="arrival_date" id="arrival_date" autofocus><br>
            <label for="nights">Nights:</label>
            <input type="text" name="nights" id="nights"><br>
            <label>Adults:</label>
            <select name="adults" id="adults">
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
            </select><br>
            <label>Children:</label>
            <select name="children" id="children">
                <option value="0">0</option>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
            </select><br>
        </fieldset>
        <fieldset>
            <legend>Preferences</legend>
            <label>Room type:</label>
            <input type="radio" name="room" id="standard" class="left" checked>Standard&nbsp;&nbsp;&nbsp;
            <input type="radio" name="room" id="business" class="left">Business&nbsp;&nbsp;&nbsp;
            <input type="radio" name="room" id="suite" class="left last">Suite<br>
            <label>Bed type:</label>
            <input type="radio" name="bed" id="king" class="left" checked>King&nbsp;&nbsp;&nbsp;
            <input type="radio" name="bed" id="double" class="left last">Double Double<br>
            <input type="checkbox" name="smoking" id="smoking">Smoking<br>
        </fieldset>
        <fieldset>
            <legend>Contact Information</legend>
            <label for="name">Name:</label>
            <input type="text" name="name" id="name"><br>
            <label for="email">Email:</label>
            <input type="text" name="email" id="email"><br>
            <label for="phone">Phone:</label>
            <input type="text" name="phone" id="phone" placeholder="999-999-9999"><br>
        </fieldset>

        <input type="submit" id="submit" value="Submit Request"><br>

    </form>
</body>
</html>

JS/JQuery

    $(document).ready(function() {
var emailPattern = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
var phonePattern = /\b(\d{3})([-])(\d{3})([-])(\d{4})\b/;
var datePattern =  /\b(0[1-9]|1[012])([/])(0[1-9]|1[0-9]|2[0-9]|3[01])([/])((20)\d\d)\b/;

$(":text").after("<span class='error'>*</span>");
$("#arrival_date").focus();

$("#reservation_form").submit(
    function(event) {
        var isValid = true;

        // validate arrival date
        var arrivalDate = $("#arrival_date").val();
        if (arrivalDate == "") {
            $("#arrival_date").next().text("This field is required");
            isValid = false;
        } else if (!datePattern.test(arrivalDate)) {
            $("#arrival_date").next().text("Must be in the format 12/12/2012");
            isValid = false;
        } else {
            $("#arrival_date").next().text("");
        }

        // validate nights
        var nights = $("#nights").val();
        if (nights == "") {
            $("#nights").next().text("This field is required");
            isValid = false;
        } else if ((isNaN(parseInt(nights))) || (parseInt(nights) <=0)) {
            $("#nights").next().text("This field must be a number and not zero");
            isValid = false;
        } else {
            $("#nights").next().text("");
        }

        // validate name
        var name = $("#name").val();
        if (name == "") {
            $("#name").next().text("This field is required");
            isValid = false;
        } else {
            $("#name").next().text("");
        }

        // validate email
        var email = $("#email").val();
        if (email == "") {
            $("#email").next().text("This field is required");
            isValid = false;
        } else if (!emailPattern.test(email) ) {
            $("#email").next().text("Must be a valid email address.");
            isValid = false;
        } else {
            $("#email").next().text("");
        }

        // validate phone
        var phone = $("#phone").val();
        if (phone == "") {
            $("#phone").next().text("This field is required");
            isValid = false;
        } else if (!phonePattern.test(phone) ) {
            $("#phone").next().text("Must be in the format 999-999-9999");
            isValid = false;
        } else {
            $("#phone").next().text("");
        }


        if (isValid == false) {
            event.preventDefault();
            $("#arrival_date").focus();
        }
    }
);


}); // end ready

Upvotes: 0

Views: 5453

Answers (1)

jimmy jansen
jimmy jansen

Reputation: 647

Most easy way is to add a Div container around the form and just append the warning to that. To effectively append after an element you need to give it a class or id.

var email = $("#email"); //using class instead of input:text
var html = "<span class='error'>TEST!</span>"
email.after( html );

But I personally would like something like this better:

var generateError = function(){
var html = "<div id='error' style='top: 0; left:0; width:100%; height: 50px; background-color: red; text-allign: center; display:none; z-index: 100;'> ERROR!!</div>"
$(body).append( html );
}

var showError = function( text ){
var err = $("#error");
err.html( text );
err.show(500).delay(2000).hide(500); 
}

Code is fairly self-explaining, but this will make two functions: generateError and showError.
generateError you need to call before you want to show the error, possibly when the page loads it will add a small header on top of all you other elements and will appear hidden.
showError uses a text argument with the error you want to show. Then it will set the text to the div and show it for two seconds.


This then is more what you are looking for?

$(document).ready(function () {
    var input = $("input");
    var emailPattern = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;

    input.keypress(function (ele) {
        // if regex.test( input ) === false
        createErrors(ele.target);
    })
});

var createErrors = function (ele) {
    $('<span>TEST!</span>').insertAfter(ele);

    $("#arrival_date").focus();
};

This works on keypress, that means the regex gets checked every time a key is pressed. It also passes the element where the user is typing as parameter, this means that you wont get errors for all input:text, but only for the ones where there is an error.

Updated Fiddle (still not perfect, but if its an school exercise this will help you to finish it :)

Upvotes: 2

Related Questions