How to make the numbers automatically using jquery append ..?
Hello all I want to ask, how to make the numbers automatically using jquery append ..? I have made it but still failed My source code is :
<html>
<head>
<title>Help Help</title>
</head>
<body>
<input type="button" id="button" value="Create a number from 1 to N"/>
开发者_如何转开发 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function ()
{
$('#button').click(function()
{
$('#result').append('<div class="number">Numbers To ......</div>');
});
});
</script>
</body>
<hr>
results from click button
<hr>
<div id=result></div>
Here's one way of doing it:
$('#numbers').change(
function(){
var max = $(this).val();
var sequence;
for(i=0; i<=max; i++) {
var text = $('#result').text();
if (text == false){
text = i;
}
else if (i == max) {
text = text + ', ' + i + '.';
}
else {
text = text + ', ' + i;
}
$('#result').text(text);
}
});
$('form').submit(
function(){
return false;
});
With the following, simplified, html:
<form action="#" method="post">
<label for="numbers">Make a sequence of numbers, from one to <em>n</em></label>
<input type="number" min="0" max="1000" step="1" id="numbers" name="numbers" />
</form>
<div id="result">
</div>
JS Fiddle demo.
Edited to offer a more concise version of the above jQuery code, as offered by mplungjan (in comments, below):
$('#numbers').change(
function(){
var max = $(this).val(),text="";
for(i=1; i<=max; i++) {
text += ', ' + i;
}
if(text) $('#result').text(text.substring(2)+".");
});
$('form').submit(
function(){
return false;
});
Revised/optimised jQuery at JS Fiddle
Answer convertd to community wiki, since earning rep from someone else's efforts just seems wrong....
精彩评论