jQuery - Check a Input Field for a Word in a String
I have users that are putting in links to youtube videos and we want to only enable the button if开发者_StackOverflow中文版 the string (URL) they enter contains the word, 'youtube'. Below is the code and I can't get it to work how I need it to. Thanks...
var inputValue = $('#inputLink').val();
$('#submitBtn').attr("disabled", "disabled");
$('#inputLink').keyup(function(){
if (inputValue.toLowerCase().indexOf("youtube") >= 0) {
$('#submitBtn').removeAttr('disabled');
}
});
You need to reinitialize inputValue
each time:
$('#submitBtn').attr("disabled", "disabled");
$('#inputLink').keyup(function(){
var inputValue = this.value;
if (inputValue.toLowerCase().indexOf("youtube") >= 0) {
$('#submitBtn').removeAttr('disabled');
}
});
Example: http://jsfiddle.net/BGcDg/
Update: You could also do this with just one line if you wanted to:
var youtubeRegex = /youtube/i;
$('#inputLink').keyup(function(){
$("#submitBtn").attr("disabled", !youtubeRegex.test(this.value));
});
This will re-disable the field if the user removes "youtube" after entering it.
Example: http://jsfiddle.net/bdmhQ/
精彩评论