mr_abbasi
mr_abbasi

Reputation: 143

Check Checkbox from the Same Row as an Input Field

I want to check the checkbox next to each html row if the select dropdown in the same row has something selected. Here is my html code and script. Can someone please point out what's wrong?

<tr>
    <td>Sohail Abbasi</td>
    <td>N&amp;S</td>
    <td>1</td>
    <td>2013-01-03</td>
    <td>Thursday</td>
    <td>09:21</td>
    <td></td>
    <td>
    <select class="form-control" name="duty_status[3]">
        <option value="" selected="selected">Select...</option>
        <option value="2">Short Leave</option><option value="5">OD</option>
    </select>                            
    </td>
    <td><input class="form-control" name="user_comments[3]" type="text"></td>
    <td>
        <input name="submit[]" type="checkbox" value="3">                
    </td>
</tr>

Javascript:

$('#SelectFilled').click(function($e)
{
    var elements=$('select[name^=duty_status]');
    var checkboxes=new Array();
    for (var i=0; i<elements.length; i++) {
        if(elements[i].value)
        {
            var parent=elements[i].parentNode.parentNode;
            checkboxes[checkboxes.length]=parent.lastChild.firstChild;
         }
    }
    for (var j=0; j<checkboxes.length; j++) {
        checkboxes[j].checked=true;
    }
});

Upvotes: 0

Views: 1399

Answers (3)

Bla...
Bla...

Reputation: 7288

Below code should works:

$('select[name^=duty_status]').on('change', function(){
    if($(this).val() != ""){ //better put some value on the first option..
         $(this).parents("tr").find(":checkbox").prop('checked', true);
    }else{
         $(this).parents("tr").find(":checkbox").prop('checked', false);
    }
});

Upvotes: 0

PeterKA
PeterKA

Reputation: 24638

You would have to use something like this:

$(function() {
    $('td > select').on('change', function() {
        var chk = $(this).closest('tr').find(':checkbox');
        chk.prop('checked', this.selectedIndex !== 0 );            
    })
    .change();
});

JSFIDDLE DEMO

Upvotes: 0

charlietfl
charlietfl

Reputation: 171679

You can simplfy your traversal code and make it far easier to read by using jQuery methods:

$('select[name^=duty_status]').each(function(){
   if( this.value === VALUE_I_WANT ){ /* not sure where this value comes from */
     $(this).closest('tr').find(':checkbox').prop('checked', true);
   } 
});

This code is based on the existing click handler triggering it. The goals in question are not very clear

Upvotes: 1

Related Questions