使用jQuery $(this)选择此表单中的任何内容

时间:2014-02-13 14:09:12

标签: javascript jquery forms this

在一个页面上有多个表单,但都具有相同的类名。

我想这样做,如果文本区域中没有内容,则禁用提交按钮。

这就像你在这里看到的那样有效:

http://jsfiddle.net/WJnqw/

但是,这显然会影响具有相同提交按钮类名的所有表单。

我尝试将代码更改为包含例如:

$(this).find(".addcommentbutton").prop("disabled", true);

我认为会选择表单,然后找到添加评论按钮。

但它不起作用。

任何帮助?

谢谢!

2 个答案:

答案 0 :(得分:1)

问题是this是窗口。你需要以某种方式传递上下文。

这是一个工作版本,它显示了指定函数中引用的this或让jquery执行它的两种方法:

http://jsfiddle.net/LVf5w/

$(document).ready(function () {
    $('.addpostcomment').each(function() {
        disableComments.call(this); // specify what "this" will be in the function
    });
    $(".addpostcomment").keyup(disableComments); //let jquery specify that "this" will be the element
});

function disableComments() {
    $(this).closest('form').find(".addcommentbutton").prop("disabled", $(this).val().length < 1);
};

您也可以这样做,而不是迭代并调用函数:

http://jsfiddle.net/LX2Dj/

$(document).ready(function () {
    $(".addpostcomment").keyup(disableComments).trigger('keyup');
});

或者(我的偏好)完全取消匿名功能:

http://jsfiddle.net/sfuHU/

$(document).ready(function () {
    $(".addpostcomment").keyup(function() {
        $(this).closest('form').find(".addcommentbutton").prop("disabled", $(this).val().length < 1);   
    }).trigger('keyup');
});

请注意,您的元素上有id个重复内容。 id必须是唯一的。

答案 1 :(得分:0)

<强> JSFIDDLE DEMO

您需要使用.next()找不到&amp;也可以在this事件

中直接使用keyup

$(this).next('.addcommentbutton').prop('disabled', !($(this).val().length > 0));

// comment form not allow submit when empty
    $(document).ready(function () {
        disableComments();
        $( ".addpostcomment" ).keyup(function() {
            $(this).next('.addcommentbutton').prop('disabled', !($(this).val().length > 0));
        });
    });

    function disableComments() {
        var commentLength = $('.addpostcomment').val().length;
        if (commentLength < 1) {
            $(".addcommentbutton").prop("disabled", true);  
        } else {
            $(".addcommentbutton").prop("disabled", false); 
        }
    };