Case insensitive jQuery attribute selector

2019-01-04 03:35发布

I am doing the following using attribute contains selector $('[attribute*=value]')

<input name="man-news">
<input name="milkMan">

<script>    
    $( "input[name*='man']").css("background-color:black");
</script>

This works for the 1st input but not the second input as "Man" has a capital "M"

How can I make $( "input[name*='man']") an case insensitive selector?

5条回答
Lonely孤独者°
2楼-- · 2019-01-04 03:52

I was just able to ignore jQuery's case sensetivity altogether to achieve what I want using below code,

            $.expr[":"].contains = $.expr.createPseudo(function(arg) {
            return function( elem ) {
                return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
            };
        });

You can use this link to find code based on your jQuery versions, https://css-tricks.com/snippets/jquery/make-jquery-contains-case-insensitive/

Also there is this article where it does to many good things with jquery: http://www.ultechspot.com/jquery/using-jquery-search-html-text-and-show-or-hide-accordingly

查看更多
贪生不怕死
3楼-- · 2019-01-04 03:54

This works for me using jQuery and if i'm adding item to a table

    // check if item already exists in table
    var inputValue = $('#input').val(); // input
    var checkitem = $('#exampleTable td.value div.editable').filter(function() {

        //check each table's editable div matches the input value in lowercase 
        if ($(this).text().toLowerCase() === inputValue.toLowerCase()) {
            itemexists = true; 
        }   
    });

    if (itemexists) {
        alert("item exists in the table");
        return;
    }
查看更多
霸刀☆藐视天下
4楼-- · 2019-01-04 04:00

The simplest way to do this is to add a case insensitivity flag 'i' inside the regex part of the selector:

So instead of

$( "input[name*='man']")

You could do

$( "input[name*='man' i]")

JS fiddle: https://jsfiddle.net/uoxvwxd1/3/

查看更多
ゆ 、 Hurt°
5楼-- · 2019-01-04 04:03

You can always use .filter():

var mans = $('input').filter(function() {
    return $(this).attr('name').toLowerCase().indexOf('man') > -1;
});

mans.css('background-color', 'black');

The key part here is toLowerCase() which lowercases the name attribute, allowing you to test it for containing man.

查看更多
等我变得足够好
6楼-- · 2019-01-04 04:11
var control = $('input').filter(function() {
    return /*REGEX_VALUE*/i.test($(this).attr('id'));
});

*REGEX_VALUE* - the value you want to find

I ended up using regex to validate whether the attribute 'ID' satisfy... regex is much more flexible if you want to find a certain matching value or values, case sensitive or insensitive or a certain range of values...

查看更多
登录 后发表回答