[英]jquery addClass not working on form element
這是我的示例tr:
<tr>
<td><input type="text" class="ingredient required" name="ingredient"></td>
<td><input type="number" class="amount required" name="amount" ></td>
<td><input type="number" class="carrier required" name="carrier" max="100"></td>
<td><input type="number" class="kilo required" name="kilo"></td>
<td><select class="tableDropDown" style="min-width: 100px;">
<option value="other">The Manufacturer</option>
<option value="me">Me</option>
</select></td>
<td><input class="packSize" type="number" disabled></td>
</tr>
<button type="submit" class="analyze">Analyze</button>
我希望它使選擇值(.tableDropDown)為“ me”時,.packSize上添加了.required類,因為我使用.required進行表單驗證。
我正在嘗試將它與jquery中的addClass方法一起使用,但是它不起作用。
這是我的代碼如下所示:
$(".tableDropDown").on('change', function () {
var packSize = $(this).parents('.formulaRow').find('.packSize');
if ($(this).val() === "me") {
$(packSize).prop('disabled', false);
$(packSize).addClass(".required");
} else {
$(packSize).prop('disabled', true);
$(packSize).parents('td').removeClass("redClass");
}
if ($(this).val() === "me" && $(packSize).val() === "") {
$(packSize).parents("td").addClass("redClass");
}
});
用於驗證的功能是這樣的:
$(".analyze").click(function() {
var counter = 0;
$(".required").each(function() {
if ($(this).val() === "") {
$(this).parents("td").addClass("redClass");
counter++;
}
});
if (counter > 0){
alert("Looks like some of the fields aren't filled out correctly. They're highlighted in red.");
}
redClass是一個CSS片段,以紅色突出顯示了td,這樣他們可以在點擊Submit之后看到需要修復的內容。
它可以與所有其他單元格一起使用,但是由於某種原因,addClass方法未添加.packSize所需的內容,我不確定為什么。
您不想在“希望”的addClass中使用“ .required”。
線
$(packSize).addClass(".required");
應該
$(packSize).addClass("required");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.