如果字段为空,则jQuery在模糊时返回原始值 [英] Jquery return original value on blur if the field left empty

查看:67
本文介绍了如果字段为空,则jQuery在模糊时返回原始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何实现?如果用户将该字段留空,我想获取原始值.

这是我到目前为止所得到的. 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);
        }
    });
});​

解决方案

您实质上是在描述 <input name="fname" placeholder="First Name">

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

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

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

此特殊垫片仅提供基本功能.其他人可能会扩展支持,以便在使用占位符值时更改字体颜色,以及在开始键入之前使占位符值可见(此方法只是将其立即移到焦点上).

Ho can I achieve this? I want to get the original value if the user left the field blank.

This is what I got so far. Jsfiddle Demo

Here is my code

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

解决方案

You're essentially describing the placeholder attribute, which is supported natively in all major browsers. It is not, however, supported in older browsers. For broader support you will need to shim support for this attribute. Many options exists online that do this for you, but you could do it yourself if you like.

Essentially you want to allow yourself, and others, to use standard markup:

<input name="fname" placeholder="First Name">

Using jQuery you would respond to the focus and blur (or focusin and focusout) events of any element having the placeholder attribute. If an element is focused, and has the placeholder value, you clear the element. If the element is blurred, and empty, you provide the placeholder value.

This is a bit verbose, but I've added comments to assist in following the logic:

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

This particular shim only provides basic functionality. Others may extend support to changing the font color when the placeholder value is used, as well as leaving the placeholder value visible until you begin typing (this approach simply removes it immediately on focus).

这篇关于如果字段为空,则jQuery在模糊时返回原始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆