简体   繁体   中英

Why won't the newly created input tags stay on page?

Im trying to create new input tags based on the number the user enters. My code will create the correct amount of tags, but they get removed almost immediately. Why?

<form>
 <input type='text' id='input' />
 <button>Submit</button>
</form>
<div id="box">
</div>

<script>
$(document).ready(function() {
 $('button').click(function() {
  var x = $('#input').val(); 
  for(var i=0 ; i < x; i++) {
        $('<input type="text" /><br>').prependTo('#box');
    };
 });
});

</script>

call preventDefault on the event to stop the button action from firing

$('button').click(function(e) {
   e.preventDefault();
   var x = $('#input').val(); 
   for(var i=0 ; i < x; i++) {
      $('<input type="text" /><br>').prependTo('#box');
   };
});

FIDDLE

Change your existing button to an input with an id and use the id in the JS. Your problem is the form is being submitted when you click button.

http://jsfiddle.net/Delorian/65gLvfdx/

<input type="button" id="update" value="Submit" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM