开发者

jQuery - Check a Input Field for a Word in a String

开发者 https://www.devze.com 2023-03-31 15:28 出处:网络
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

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/

0

精彩评论

暂无评论...
验证码 换一张
取 消