在一個頁面上有多種形式,但都具有相同的類名。
我想這樣做,如果文本區域中沒有內容,則提交按鈕將被禁用。
這工作,你可以在這裏看到我這樣做是:
然而,這顯然會影響到所有的形式用相同的提交按鈕類名。
我試圖改變的代碼包括e.g:
$(this).find(".addcommentbutton").prop("disabled", true);
,因爲我以爲這將選擇窗體,並找到新增評論按鈕。
但它不工作。
任何幫助?
謝謝!
在一個頁面上有多種形式,但都具有相同的類名。
我想這樣做,如果文本區域中沒有內容,則提交按鈕將被禁用。
這工作,你可以在這裏看到我這樣做是:
然而,這顯然會影響到所有的形式用相同的提交按鈕類名。
我試圖改變的代碼包括e.g:
$(this).find(".addcommentbutton").prop("disabled", true);
,因爲我以爲這將選擇窗體,並找到新增評論按鈕。
但它不工作。
任何幫助?
謝謝!
的問題是,this
是WINDO W上。您需要以某種方式傳遞環境。
這裏有一個工作版本,顯示的任何指定什麼this
的功能是指或者讓jQuery的兩種方式做到這一點:
$(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);
};
你也可以只做到這一點,而不是迭代和調用函數:
$(document).ready(function() {
$(".addpostcomment").keyup(disableComments).trigger('keyup');
});
或(我偏好)與完全的匿名函數做掉:
$(document).ready(function() {
$(".addpostcomment").keyup(function() {
$(this).closest('form').find(".addcommentbutton").prop("disabled", $(this).val().length < 1);
}).trigger('keyup');
});
請注意,您在您的元素有重複id
秒。 id
必須是唯一的。
完美的,謝謝你的更簡單的方法!我並沒有打算在同一頁面上使用這種ID的多種形式。將刪除id和它不需要,並堅持與類 – Lovelock
您需要使用.next()
找不到&也直接在keyup
事件中使用this
$(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);
}
};
**注意:** ID必須是唯一的。 – Anton