简体   繁体   中英

dynamic add input in javascript

I'm new at javascript and I need some help making sense of this code and why it's not working.

<html>
<head>
    <title></title>
</head>
<body>

    <form action="" method="POST">
        <input id="in" type="text" name="name">
    </form>
    <button id="add">addone</button>

    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script>
        $('#add').click(function() {
          $('#in').append('<br /><input type="text" name="name">');
        });

    </script>

</body>
</html>

I'm trying to append another html input but I have no ideas why it's not working!?.

An input is self-closing, it has no children, and you can't append to it.

You can however insert something after it

$('#in').after('<br /><input type="text" name="name">');

 <html> <head> <title></title> </head> <body> <form action="" method="POST"> <input id="in" type="text" name="name"> </form> <button id="add">addone</button> <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script> <script> $('#add').click(function() { $('#in').after('<br /><input type="text" name="name">'); }); </script> </body> </html> 

Note that your duplicating the name, and depending on what you indend to do with it, using name[] could be a good idea ?

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