如果选中,则禁用表单

If checked then disabled form

本文关键字:表单 如果      更新时间:2024-03-06

我有这些代码:

<div class="nested-fields">
  <div class="row">
    <div class="col-sm-4">
      <div class="form-group">
        <%= f.input :start_work, as: :date, start_year: Date.today.year - 20,
                                            end_year: Date.today.year, ignore_day: true,
                                            order: [:month, :year],
                                            input_html: { class: 'form-control' },
                                            label: 'Start work period' %>
      </div>
      <div class="form-group">
        <%= f.input :is_current, label: 'Currently work here', input_html: { class: 'current' } %>
      </div>
    </div>
    <div class="col-sm-4">
      <div class="form-group">
        <%= f.input :end_work, input_html: {class: 'end_work'}, as: :date, start_year: Date.today.year - 20,
                                            end_year: Date.today.year, ignore_day: true,
                                            order: [:month, :year],
                                            input_html: { class: 'form-control' },
                                            label: 'End work period' %>
      </div>
    </div>
  </div>
</div>
<script>
  $(document).ready(function() {
    // experience current work
    $(".current").each(function() {
      $(this).click(function() {
        var isCurrent = $(this).prop("checked");
        if (isCurrent == true) {
          $(this).closest('.form-group').next('.form-group').find('.end_work').prop("disabled", "disabled");
        }
        else {
          $(this).closest('.form-group').next('.form-group').find('.end_work').prop("disabled", false);
        }
      });
    });
  });
</script>

但是,当选中当前框时,我无法禁用end_work输入。我想我错过了Javascript上的目标类或其他内容。任何帮助都会很棒!

$(this).closest('.form-group').next('.form-group')不会做你认为它会做的事情。div.form-group在DOM中不是兄弟,所以,如果我没有弄错的话,.next('.form-group')将找不到任何东西。

尝试$(this).closest('.col-sm-4').next('.col-sm-4').find('.end_work')


顺便说一句,这个代码是多余的:

$(".current").each(function() {
  $(this).click(function() {
    ...

因为CCD_ 5已经向选择器匹配的每个元素附加了点击处理程序。你只需一行就可以完成同样的事情:

$(".current").click(function() {
  ...