Question

I use a table for an invoice form and want to add/remove dynamically columns with taxes.

My Selectbox:

<select id="tax" class="form-control tax" onchange="SetTax();">
<option value="tax-none" selected="selected">No</option>    
<option value="1 Tax">1 Tax</option>
<option value="2 Taxes" selected="selected">2 Taxes</option>
</select>

Columns for Taxes in my table (id: #table-document)

<th><textarea type="text" class="header-inputs tax1-header" data-i18n="table.tax" style="overflow: hidden; word-wrap: break-word; resize: none; height: 38px;">Tax</textarea></th>

<td class="tax1-column">
    <input data-key="tax1" class="table-inputs tax1-row" autocomplete="off" value="0%">
</td>

<th><textarea type="text" class="header-inputs tax2-header" data-i18n="table.tax" style="overflow: hidden; word-wrap: break-word; resize: none; height: 38px;">Tax</textarea></th>

<td class="tax2-column">
    <input data-key="tax2" class="table-inputs tax2-row" autocomplete="off" value="0%">
</td>

In my table (#table-document, with thead, tbody and tfoot), the positions of columns for the taxes are No. 5 and 6.

Now I´m looking for a way to add / remove the columns, depending on the value of my selectbox.

Actually, I use a jQuery function with about 40 lines, but it still does not work. Is there any efficient way to do this?

Was it helpful?

Solution

Try:

jQuery:

$('#tax').change(function() {

    var $first = $('table').find('tr').find('td:nth-child(5)'),
        $second = $('table').find('tr').find('td:nth-child(6)'),
        $v = $(this).val();

    $first.hide();
    $second.hide();

    if ($v == 'tax-one') $first.show();
    else if ($v == 'tax-two') $second.show();
});

HTML:

<select id="tax" class="form-control tax">
    <option value="tax-none" selected="selected">No</option>    
    <option value="tax-one">1 Tax</option>
    <option value="tax-two">2 Taxes</option>
</select>

<hr />

<table>
<tbody>
    <tr><td></td><td></td><td></td><td></td><td>Tax 1</td><td>Tax 2</td></tr>    
    <tr><td></td><td></td><td></td><td></td><td>Tax 1</td><td>Tax 2</td></tr>    
    <tr><td></td><td></td><td></td><td></td><td>Tax 1</td><td>Tax 2</td></tr>    
    <tr><td></td><td></td><td></td><td></td><td>Tax 1</td><td>Tax 2</td></tr>    
    <tr><td></td><td></td><td></td><td></td><td>Tax 1</td><td>Tax 2</td></tr>        
    </tbody>
</table>

DEMO

OTHER TIPS

use show() and hide() methods for dynamically display and hide your columns. $('taxcolumn').show() or $('taxcolumn').hide() , where taxcolumn is the column id.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top