使用Jquery将带有Class的Span添加到输入标记

时间:2015-03-08 03:37:22

标签: javascript jquery html

我正在尝试在输入后添加一个Span,它将包含“错误”类和文本“test”。

我已经尝试过append和insertAfter方法。我可以让代码在jsfiddle上工作,但我无法让代码在我的应用程序上运行。

我已将HTML和JS / Jquery放在下面。我的最终结果将在具有类型文本的每个输入旁边具有Span(具有类错误)。然后,我将根据验证循环为此范围设置一个值。

    <!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

1 个答案:

答案 0 :(得分:1)

最简单的方法是在表单周围添加一个Div容器,然后向其添加警告。要在元素之后有效追加,您需要为其提供类或ID。

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

但我个人更喜欢这样的事情:

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

代码是相当自我解释的,但这将产生两个函数:generateError和showError。
在您想要显示错误之前需要调用的generateError,可能在页面加载时会在所有其他元素的顶部添加一个小标题并显示为隐藏。
showError使用带有要显示的错误的文本参数。然后它将文本设置为div并显示它两秒钟。

<小时/> 那么这更像是你在寻找什么?

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

这适用于按键,这意味着每次按下按键时都会检查正则表达式。它还传递用户键入的元素作为参数,这意味着您不会为所有输入:文本获取错误,但仅针对出现错误的文本。

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