如果字段留空,则Jquery返回模糊的原始值

Dip*_*ips 4 jquery jquery-validate

何我能实现这个目标吗?如果用户将该字段留空,我想获取原始值.

这是我到目前为止所得到的.Jsfiddle演示

这是我的代码

$(document).ready(function() {
    var field = $('input[type="text"]');
    field.focus(function() { //Empty the field on focus
        var thisValue = $(this).val();
        $(this).attr("value", "");
    });

    field.blur(function() { //Check the field if it is left empty
        if ($(this).val() == "") {
            //alert('This field can not be left empty');
            $(this).val(thisValue);
        }
    });
});?
Run Code Online (Sandbox Code Playgroud)

Sam*_*son 5

您实际上是在描述该placeholder属性,该属性在所有主流浏览器中都是本机支持的.但是,旧版浏览器不支持它.要获得更广泛的支持,您需要对此属性进行补充.网上有许多选项可供您使用,但如果您愿意,可以自己动手.

基本上你想让自己和其他人使用标准标记:

<input name="fname" placeholder="First Name">
Run Code Online (Sandbox Code Playgroud)

使用jQuery你的反应focusblur(或focusinfocusout具有任何元素)的事件placeholder属性.如果元素已聚焦且具有占位符值,则清除该元素.如果元素模糊且为空,则提供占位符值.

这有点冗长,但我添加了注释以帮助遵循逻辑:

// Written and tested with jQuery 1.8.1
(function ( $ ) {

    // Play nice with jshint.com
    "use strict";

    // Abort if browser already supports placeholder
    if ( "placeholder" in document.createElement("input") ) {
        return;
    }

    // Listen at the document level to work with late-arriving elements
    $(document)
        // Whenever blur or focus arrises from an element with a placeholder attr
        .on("blur focus", "[placeholder]", function ( event ) {
            // Determine the new value of that element
            $(this).val(function ( i, sVal ) {
                // First store a reference to it's placeholder value
                var placeholder = $(this).attr("placeholder"), newVal = sVal;
                // If the user is focusing, and the placehoder is already set
                if ( event.type === "focusin" && sVal === placeholder ) {
                    // Empty the field
                    newVal = "";
                }
                // If the user is blurring, and the value is nothing but white space
                if ( event.type === "focusout" && !sVal.replace(/\s+/g, "") ) {
                    // Set the placeholder
                    newVal = placeholder;
                }
                // Return our new value
                return newVal;
            });
        })
        // Finally, when the document has loaded and is ready
        .ready(function () {
            // Find non-autofocus placeholder elements and blur them
            // This triggers the above logic, which may provide default values
            $(":input[placeholder]:not([autofocus])").blur();
        });

}(jQuery));
Run Code Online (Sandbox Code Playgroud)

此特定垫片仅提供基本功能.其他人可以在使用占位符值时扩展对更改字体颜色的支持,以及在开始键入之前保持占位符值可见(此方法只是在焦点时立即删除它).