jQuery advanced selector and filter methods

Jquery it’s a powerful framework that allows us to apply advanced client side selectors and filters using elegant and readable code. Basic selectors can be applied using following method: $(‘tr’). If we want to apply an filter to our results we can use it like that: $(‘tr:eq(1)’) which gets first tr element with the index 1.

Lets create an example with the table that has currency values we want to convert.

jquery-selectors

In our example we add styles to our existing table, next we set the first row color to red. Next, we append 9 more rows with some values. Next, we give gray color to the even rows with index greater than 1 $(‘tr:even:gt(1)’). After that we set the last row color to be equal the first one (non header row).

Next step is to convert each row value from pounds to dollars using each function. After that we set some styles to the button with value “Reset” and link with text “Add”.

At the end we catch the submit event and display the hidden form value in the confirmation dialog. See the in-line comments below.

 $(document).ready(function () {
    //set the table css
    $('table').addClass('myTable');

    //set first row color to red (after header)
    $('tr:eq(1)').css('background-color', 'red');

    //add some rows to table
    for (var i = 1; i < 10; i++) {
        $('table').append("<tr><td>Client " + i + "</td><td>" + 10 + i + "</td></tr>");
    }

    //set even row background color (with index more than 1)
    $('tr:even:gt(1)').css('background-color', 'silver');

    //set backround of last row to be same as the first row (non header)
    $('tr:last').css('background-color', $('tr:eq(1)').css('background-color'))

    //insert after second child
    $('th:nth-child(2)').text('Total (£)').after('<th>Total ($)</th>');

    //convert each value after second child for each row
    $('td:nth-child(2)').after('<td/>').each(function () {
        $(this).next().text((parseInt($(this).text()) * 1.5).toFixed(0));
    });

    //find the button with value reset and link with text add and give it some styles
    $(':submit[value="Reset"], a:contains("Add")').css('float', 'left').css('margin', '5px').css('color', 'green');

    //catch the submit action and read hidden value
    $('form[action$="/Reset"]').submit(function () {
        var summitName = $(':hidden', this).attr('value');
        return confirm('Are you sure you want to Reset ' + summitName + ' ?');
    });

});

Included sample it’s barely an tip of the iceberg of what we can achieve with jQuery. Please read jQuery documentation if you need more information on this topic. I have included working example below for your tests.
jQuery-selectors-filters

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...