Reputation: 167
I have the following code and am trying to get the number entered by the user to create that amount of rows with a counter in the cells up to the number entered(ie. if user enters 6, 6 rows will appear with 1-6 in them, 1 at the top) I figure a for-loop would work well, but I can't figure out what variables work. Any help would be greatly appreciated!
$(document).ready(function() {
$('#nbrTxt').focus();
var index = 1;
$('input[name=nbrTxt]').on('keyup', function(e) {
if (e.which === 13) {
$('table').append('<tr><td></td><td></td></tr>');
$('table tr:last td:first').html($(this).val());
$('table tr:last td:last').html(index);
$(this).focus().select();
index++;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<title> JQuery Selector</title>
<style type="text/css">
body {
font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif;
}
</style>
<script src="jquery-1.11.3.min.js"></script>
<script src="jqueryselector.js"></script>
</head>
<body>
<h1>JQuery Selector</h1>
Enter Number:
<input type="number" name= "nbrTxt" id="nbrTxt" />
<input type="button" value="GO" id="btnGo"/>
<table id="table" width="500" border="1">
<tr>
<td>No. Count</td>
<td>Name</td>
</tr>
</table>
</body>
Upvotes: 0
Views: 35
Reputation: 3823
Try this. I just changed keyup event to click though, but it should work.
$(document).ready(function() {
$('#nbrTxt').focus();
$('#btnGo').on('click', function(e) {
var value = $('#nbrTxt').val();
for (var i = 1; i <= value; i++) {
$('table').append('<tr><td></td><td></td></tr>');
$('table tr:last td:first').html(value);
$('table tr:last td:last').html(i);
}
});
});
Upvotes: 2
Reputation: 2295
Yes, you can use a for loop.
$(document).ready(function() {
$('#nbrTxt').focus();
$('input[name=nbrTxt]').on('keyup', function(e) {
var index = parseInt($(this).val());
if (e.which === 13) {
for(var i = 1; i <= index; i++) {
$('table').append('<tr><td>' + i + '</td><td></td></tr>');
$(this).focus().select();
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<title> JQuery Selector</title>
<style type="text/css">
body {
font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif;
}
</style>
<script src="jquery-1.11.3.min.js"></script>
<script src="jqueryselector.js"></script>
</head>
<body>
<h1>JQuery Selector</h1>
Enter Number:
<input type="number" name= "nbrTxt" id="nbrTxt" />
<input type="button" value="GO" id="btnGo"/>
<table id="table" width="500" border="1">
<tr>
<td>No. Count</td>
<td>Name</td>
</tr>
</table>
</body>
Upvotes: 1