sinesine sinesine - 1 month ago 5
jQuery Question

Using button to reset value in a table

I'm trying to get a button to reset one of the values in my table, however it's not working. Here is the code:

HTML

<table class="table table-bordered" id="table">
<thead>
<tr>
<th>Time</th>
<th>Header</th>
<th>Header</th>
<th>Header</th>
</tr>
</thead>
<tbody>
<tr>
<td id="time" data-default="00:00">48:25</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
</tr>
</tbody>
</table>

<button type="button" class="btn btn-block btn-danger" id="reset">Reset</button>


jQuery

$(document).ready(function() {
$("#reset").on("click", function() {
$('#table').find('#time').each(function() {
$(this).val($(this).attr("data-default"));
});
});


JSFiddle

Any help would be greatly appreciated.

Answer

A TD element doesn't have a value, it has text content, so you'd use text(), and you could use a callback to return the data-attribute

$(document).ready(function() {
    $("#reset").on("click", function() {
        $('#time').text(function() {
        	return $(this).data('default');
        })
    });
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table class="table table-bordered" id="table">
    <thead>
        <tr>
            <th>Time</th>
            <th>Header</th>
            <th>Header</th>
            <th>Header</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td id="time" data-default="00:00">48:25</td>
            <td>Data</td>
            <td>Data</td>
            <td>Data</td>
        </tr>
    </tbody>
</table>

<button type="button" class="btn btn-block btn-danger" id="reset">Reset</button>