jQuery 1.9.1 property selector

北城余情 提交于 2019-11-30 08:24:43

Using .filter seems to be the only way, but it's not too bad and you can actually make it a little more accurate by using .val:

$(":input").filter(function () { return $(this).val() === ""; });

If this really is that reprehensible to you, you could create a custom selector.

$.expr[':'].emptyInput = function (elem) {
    return $(elem).is(":input") && $(elem).val() === "";
};

http://jsfiddle.net/ExplosionPIlls/zaZPp/

EDIT: You may also be able to get away with using this.value instead of $(elem).val().

According to the upgrade guide:

However, when a selector like "input[value=abc]" is used, it should always select by the value attribute and not any change made to the property by the user, for example from them typing into a text input. As of jQuery 1.9, this behaves correctly and consistently. Earlier versions of jQuery would sometimes use the property when they should have used the attribute.

So this answers your first question - there is not a direct equivalent, the point is to use the attribute instead of the property.

Your code seems fine, but if you want to be more standardized and re-usable you could create an additional filter. Like so:

(function($) {
    $.expr[':'].hasValue = function(element) {
        var $element = $(element);
        return element.is(':input') && element.val();
    };
}(window.jQuery));

This will allow you to select stuff like that:

// Select input elements with value and select elements without value.
$('input:hasValue,select:not(:hasValue)');

And other various combinations you need.

I came across this and just wanted to post another solution I found that works in some situations where some of the other suggested solutions are not appropriate.

Simply add this event handler to your code

    $('input').on('keyup', function(){  
        var value = $(this).val();
        $(this).attr('value', value);
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!