0

I'm very new to Javascript. I want to avoid multiple selection for each "row". I found an example here but it remove attributes of all the selects in the page. I tried to tweak it to support only the table row but no such luck. Could someone please help! Below is the code snippet.

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

This is my table structure

<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>

2
  • Please show relevant html structure Commented Oct 30, 2016 at 16:32
  • Just added the structure :) Commented Oct 30, 2016 at 16:44

1 Answer 1

1

Without any html shown I will assume the following would do what you need.

You want to isolate instances in that row by first traversing up to the <tr> using closest() and then looking inside that <tr> for <select> elements that only exist in that row using 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');
        }
    });
});​
Sign up to request clarification or add additional context in comments.

2 Comments

Remember this pattern...it is very common for repeating structures in a page
Thank you sensei! im still a noob

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.