what is the best way of finding out if a text input includes a 开发者_StackOverflowspecific 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;
}
});
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/
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
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
.
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
精彩评论