tugberk
tugberk

Reputation: 58444

finding out if a text input includes a specific text with jquery

what is the best way of finding out if a text input includes a specific text with JQuery?

For example, how can I find out and return a Boolean result if $('#poo').val() includes airport?

EDIT

Here is the solution to my problem thanks to @Niklas;

var IsbtFortxtPropertyHotelNameOn = false;
$('#<%: txtPropertyHotelName.ClientID %>').keyup(function() { 

    if (/airport/i.test(this.value) && !IsbtFortxtPropertyHotelNameOn) { 
        $('#<%: txtPropertyHotelName.ClientID %>').btOn();
        IsbtFortxtPropertyHotelNameOn = true;
    } else if(IsbtFortxtPropertyHotelNameOn && !/airport/i.test(this.value)) {
        $('#<%: txtPropertyHotelName.ClientID %>').btOff();
        IsbtFortxtPropertyHotelNameOn = false;
    }
});

Upvotes: 3

Views: 103

Answers (4)

Ruslan
Ruslan

Reputation: 10147

normally you'd do it with either indexOf or split functions, e.g.

$("#textInput").val().split("specifictext").length > 0

there's also Contains Selector:

Description: Select all elements that contain the specified text.

which serves a slightly different purpose but may be of use to you

Upvotes: 1

Niklas
Niklas

Reputation: 30002

If you want to have control over the case-sensitivity, you could use regex:

if (/airport/i.test(this.value)) alert('true');

It becomes especially useful if you need to check for multiple variables instead of just airport:

if (/(airport|station|docks)/i.test(this.value)) alert('true');

http://jsfiddle.net/niklasvh/tHLdD/

Upvotes: 4

Jos&#233; Leal
Jos&#233; Leal

Reputation: 8109

Don't really know if it's the best way.. but

function findInpWithTxt(txt) {
    var t = null;
    $("input[type=text]").each(function() {
        if ($(this).val().indexOf(txt) >= 0) {
            t = this;
            return false;
        }
    });
    return t;
}

this will return the input if found, null if not

Upvotes: 0

James Allardice
James Allardice

Reputation: 165951

if($("#elementId").val().indexOf("airport") != -1) {
    //Contains "airport"
}

The JavaScript indexOf function returns the index of the first occurence of the specified string. If the string is not found, it returns -1.

Upvotes: 0

Related Questions