Add Textbox value to table using jQuery
by Avinashullal
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table class="table">
<tr>
<td>
<input type="text" name="input" class="form-control" id="Text1" width="200" />
</td>
<td>
<button id="btnAdd" type="button" class="btn btn-success">Add</button>
</td>
</tr>
</table>
<br />
<div class="table-responsive">
<table class="table table-striped table-hover table-bordered" id="table1">
<thead>
<tr>
<th style="width: 99%">Links</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
CSS
html {
height: 100%;
position: relative;
}
body {
background-color: #fff;
height: 100%;
font-family: Segoe UI, Open Sans;
font-size: 14px;
color: #393939;
line-height: 1.5;
padding: 20px;
}
h1,
h2,
h3,
h4,
h5,
h6,
.h1,
.h2,
.h3,
.h4,
.h5,
.h6 {
font-family: Segoe UI Light, Open Sans, sans-serif;
font-weight: 100;
}
.deleterow {
cursor: pointer
}
JavaScript
$(document).ready(function() {
$('#btnAdd').click(function(e) {
e.preventDefault(); // this is how to stop the form submitting
var val1 = $('#Text1').val(); // us an id selector - it is much better performance
if (val1 != '') { // check if textbox was empty (not sure what your loop did)
$('#table1 tbody').append('<tr><td>' + val1 + '</td><td><a href="#" class="deleterow glyphicon glyphicon-remove"></a></td></tr>'); //apend new row to table
}
$('#Text1').val("");
});
$(document).on('click', '.deleterow', function(e) {
$(this).closest("tr").remove();
});
});