M_T M_T - 1 month ago 6
Javascript Question

Prevent multiple selection for each row with Javascript

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



Answer

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