2016-10-30 40 views
0

我對JavaScript很陌生。我想避免每個「行」的多個選擇。我找到一個示例here,但它刪除頁面中所有選擇的屬性。我試圖調整它只支持錶行,但沒有這樣的運氣。有人可以請幫忙!以下是代碼片段。防止使用Javascript對每一行進行多重選擇

$('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> 

+0

首先遍歷到<tr>,然後尋找那個<tr><select>元素,只有該行中存在內部隔離該行情況請出示相關的HTML結構 – charlietfl

+0

剛剛添加的結構:) –

回答

1

沒有顯示我將承擔以下會做你所需要的任何HTML。

你想用closest()使用find()

$('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'); 
     } 
    }); 
});​ 
+0

你是一個救星@charlieft!奇蹟般有效! –

+0

請記住這個模式......它在頁面中重複結構是非常常見的 – charlietfl

+0

謝謝sensei!即時通訊仍然是一個菜鳥 –