1

html:

<h1>Favorite Animal:</h1>
<input type='text'>
<button>Answer!</button>
<div id='ans'></div>

Javascript (jQuery)

$(document).ready(function(){
    $('button').click(function(){
        $('#ans').append('<h2>Bunny</h2>')
    })
})

Hey there. I was wondering. Can I make it so that when I type a number into the input[type='text'] and then have that number of "bunny" appear? (example: I type in 3, the word "bunny" appears 3 times).

Rajendran Nadar
  • 2,413
  • 2
  • 21
  • 34
Lucian cahil
  • 71
  • 1
  • 7

5 Answers5

1

You can do it with a simple loop:

$(document).ready(function() {
  $('button').click(function() {
    for (i = 0; i < $('input[type=text]').val(); i++) {
      $('#ans').append('<h2>Bunny</h2>')
    }
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' />
<button>Answer!</button>
<div id='ans'></div>
SLePort
  • 14,405
  • 3
  • 28
  • 39
0

No problem, just create an array with that many indices, and fill it

$(document).ready(function() {
  $('button').click(function() {
    var n   = +$('input').val();
    var arr = $.map(Array(n), function() {
      return $('<h2 />', {text : 'Bunny'});
    });

    $('#ans').empty().append(arr);
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>
  Favorite Animal:
</h1>
<input type='text'>
<button>
Answer!
</button>
<div id='ans'>

</div>
adeneo
  • 293,187
  • 26
  • 361
  • 361
  • Maybe it's worth mentioning that the `fill` method is not supported by all browsers(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill#Browser_compatibility). – SLePort Sep 10 '17 at 06:40
  • @SLePort - correct, `Array.fill` isn't supported in IE, but MDN has a polyfill – adeneo Sep 10 '17 at 06:53
  • 1
    Fortunately, jQuery has a way around that – adeneo Sep 10 '17 at 06:55
0

Yes, you can get the input typed by the user, convert it from a string to a number, check if it's a whole number between 1 and 1000 and use it in a for loop. Each time add the element in the for loop. Here are some examples How can val() return Number? you can use a slider to do this an use html attributes to make sure the number is as you expect it to be

Maarten Arits
  • 150
  • 1
  • 9
0

More efficiently you can do:

$(document).ready(function(){
    $('button').click(function(){
        $('#ans').append('<h2>Bunny</h2>'.repeat($('input').val()))
    })
})
antoni
  • 3,652
  • 25
  • 37
0
You may try for This:

 1. In JS part:


    $(document).ready(function() {
          $('button').click(function() {
            for (i = 0; i < $('input[type=text]').val(); i++) {
              $('#ans').append('<h2>Bunny</h2>')
            }
          })
        })

 2. in HTML part:

     <input type='text' />
    <button>Answer!</button>
    <div id='ans'></div>
Kunvar Singh
  • 1,591
  • 10
  • 20