3

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

4 Answers 4

4

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Nice touch there. the best one. I am gonna use it blur event instead of keyup. thanks !
1

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

Comments

0
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.

Comments

0

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

1 Comment

Sorry, didn't read the update, for me he was looking for all of them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.