0

I'd like to toggle the visibility of certain rows in a table based on the value of a drop-down box. I already have classes for each of the rows, so I decided to add userType as an attribute (which is generated by PHP) to the <tr>'s. However, when I use the same function I used for toggling the visibility of the rows using their class selectors, it doesn't work with $('tr[userType="User"]');. I've searched around for why this selector isn't returning the right array, but haven't had any luck. Any help would be much appreciated.

Function:

function toggleUserTypeRows(){
    var selected = $('#userTypeDropDown').val();
    switch (selected){
        case 'User':
            var $rows = $('tr[userType="User"]');
            $rows.show();
            $('tr[userType="Admin"]').hide();
            break;

        case 'Admin':
            var $rows = $('tr[userType="Admin"]');
            $rows.show();
            $('tr[userType="User"]').hide();
            break;
        default:
            var $rows = $('#tableUsers tr');
            $rows.show();
    }
}
1
  • Isn't it possible that jQuery interprets [userType] as <tr user-type=""> ? Commented Oct 18, 2011 at 20:20

2 Answers 2

1
<table>
    <tr userType="Admin"><td>Row 1</td></tr>
    <tr userType="User"><td>Row 2</td></tr>  
    <tr userType="Admin"><td>Row 3</td></tr>
    <tr userType="User"><td>Row 4</td></tr>     
 </table>


<select>
    <option value="User">User</option>
    <option value="Admin">Admin</option>
</select>

<script type="text/javascript">

$('select').change(function(e){
    var userType = $(this).val();
    $('table tr').show();
    $('table tr[userType="'+ userType +'"]').hide();
});

</script>
Sign up to request clarification or add additional context in comments.

Comments

1

Use filter()

For example:

     case 'User':
        var $rows = $('tr').filter(function(){
             return $(this).attr('userType') == 'User';
        });
        ...

Comments

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.