简体   繁体   English

jQuery addClass在表单元素上不起作用

[英]jquery addClass not working on form element

Here's my example tr: 这是我的示例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>

I want it so that when the select value (.tableDropDown) is "me", .packSize has the class .required added on to it, because I use the presence of .required for form validation. 我希望它使选择值(.tableDropDown)为“ me”时,.packSize上添加了.required类,因为我使用.required进行表单验证。

I'm trying to use this with the addClass method in jquery but it's not working. 我正在尝试将它与jquery中的addClass方法一起使用,但是它不起作用。

This is what my code looks like: 这是我的代码如下所示:

 $(".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");
    }
});

The function that's being used for the validation is this: 用于验证的功能是这样的:

$(".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 is a CSS snippet that highlights the td in red so they can see what needs to be fixed after hitting submit. redClass是一个CSS片段,以红色突出显示了td,这样他们可以在点击Submit之后看到需要修复的内容。

It works with all the other cells, but for some reason the addClass method is not adding required to .packSize and I"m not sure why. 它可以与所有其他单元格一起使用,但是由于某种原因,addClass方法未添加.packSize所需的内容,我不确定为什么。

You don't want to use ".required" in addClass you want it be "required". 您不想在“希望”的addClass中使用“ .required”。

The line 线

$(packSize).addClass(".required");

should be 应该

$(packSize).addClass("required");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM