Skip to content
Advertisement

How do I fill a cell in the table dynamically?

How do I fill a cell in the table dynamically after the user selects an option within the column?

Inside the select there is an update function and it is working, but I can’t update column two of the line with the data given value of the select.

function update(line) {
    // update in the col of mytable for next col.
    // whats wrong with this code? 
    // Why not working?
    var td = line.closest('td');
    td.nextSibling.innerText = line.value;       
}
    <table id="myTable">
        <thead>
            <tr>
                <td>Selection</td>
                <td>Value</td>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>
                    <div class='form-group col-md-12 col-xs-12'>
                        <select id="item1" onChange='update(this)' class='options' name='choice'>
                            <option value='option1'>option1</option>
                            <option value='option2'>option2</option>
                            <option value='option3'>option3</option>
                            <option value='option4'>option4</option>
                        </select>
                    </div>
                </td>
                <td id='emilio'>
                    1
                </td>
            </tr>
            <tr>
                <td>
                    <div class='form-group col-md-12 col-xs-12'>
                        <select id="item1" onChange='update(this)' class='options' name='choice'>
                            <option value='option1'>option1</option>
                            <option value='option2'>option2</option>
                            <option value='option3'>option3</option>
                            <option value='option4'>option4</option>
                        </select>
                    </div>
                </td>
                <td>
                    2
                </td>
            </tr>
        </tbody>
    </table>

     

Advertisement

Answer

Since the onChange is working, you need to select the containing td then update then next one like:

function onChange(update) {
            var td = update.closest('td');
            td.nextElementSibling.innerText = update.value;
        }
Advertisement