【问题标题】:Prevent multiple selection for each row with Javascript防止使用Javascript对每一行进行多项选择
【发布时间】:2017-03-12 21:14:02
【问题描述】:

我对 Javascript 很陌生。我想避免对每个“行”进行多项选择。我找到了一个示例here,但它删除了页面中所有选择的属性。我试图调整它以仅支持表格行但没有这样的运气。有人可以帮忙吗!下面是代码sn-p。

$('select').change(function() {
    var ary = new Array();
    $('select option:selected').each(function() {
        if ($(this).val().length > 0) {
            ary.push($(this).val());
        }
    });
    $('select option').each(function() {
        if ($.inArray($(this).val(), ary) > -1) {
            $(this).attr('disabled', 'disabled');
        } else {
            $(this).removeAttr('disabled');
        }
    });
});​

这是我的表结构

<tr>
   <td class="col-md-6">
       <select name="from[]" class="form-control single-select" id="from">
          <?php foreach($arrStops as $a){?>
               <option value="<?php echo implode($a) ?>"> <?php echo implode($a) ?></option>
         <?php } ?>
       </select>
   </td>
   <td class="col-md-6">
        <select name="to[]" class="form-control single-select" id="to">
          <?php foreach($arrStops as $a){ ?>
            <option value="<?php echo implode($a) ?>"> <?php echo implode($a) ?></option>
          <?php } ?>
        </select>
  </td>

【问题讨论】:

  • 请显示相关的html结构
  • 刚刚添加了结构:)

标签: javascript jquery html-table row


【解决方案1】:

如果没有显示任何 html,我将假设以下内容可以满足您的需求。

您想隔离该行中的实例,首先使用closest() 遍历&lt;tr&gt;,然后使用find()&lt;tr&gt; 内部查找仅存在于该行中的&lt;select&gt; 元素

$('select').change(function() {
    // isolate row instance
    var $row = $(this).closest('tr');

    var ary = new Array();
    // only look inside row
    $row.find('select option:selected').each(function() {
        if ($(this).val().length > 0) {
            ary.push($(this).val());
        }
    });
    $row.find('select option').not(':selected').each(function() {
        if ($.inArray($(this).val(), ary) > -1) {
            $(this).attr('disabled', 'disabled');
        } else {
            $(this).removeAttr('disabled');
        }
    });
});​

【讨论】:

  • 记住这种模式...在页面中重复结构很常见
  • 谢谢老师!我还是个菜鸟
猜你喜欢
  • 2017-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-12
相关资源
最近更新 更多