JavaScript - Generate Input Field Using jQuery
Submitted by razormist on Saturday, October 5, 2019 - 20:33.
In this tutorial we will create a Generate Input Field using jQuery. This code will dynamically generate new input field when the user click the add button. The code itself use jQuery onclick function to generate new input field using appendTo() a jQuery built-in function that will append all the elements as a child of the parent element. This is a user-friendly program feel free to modify it.
We will be using jQuery a JavaScript framework that design to simplify HTML DOM tree traversal and manipulation. It can do more in a single line of code than JavaScript can do in a whole function.
There you have it we successfully created a Generate Input Field using jQuery. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
Getting Started:
This is the link for the bootstrap that i used for the layout design https://getbootstrap.com/. And this is the link for the jquery that i used in this tutorial https://jquery.com/.The Main Interface
This code contains the interface of the application. To create this just write these block of code inside the text editor and save this as index.html.- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
- <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
- </head>
- <body>
- <nav class="navbar navbar-default">
- <div class="container-fluid">
- </div>
- </nav>
- <div class="col-md-6 well">
- <hr style="border-top:1px dotted;"/>
- <div class="col-md-4">
- <form>
- <div class="form-group">
- <input type="text" id="input" class="form-control"/>
- </div>
- <br />
- </form>
- </div>
- </div>
- </body>
- </html>
Creating the Script
This code contains the script of the application. This code will generate an input field when the button is clicked. To do this just copy and write these block of codes as shown below inside the text editor and save it as script.js inside the js directory- $(document).ready(function(){
- $('#add').on('click',function(){
- var input = $('#input').val();
- if(input != ""){
- $('#submit').show();
- var newInput = $(
- '<div class="form-group">'
- +'<input type="text" placeholder="'+input+'" class="form-control newInput" required="required"/>'
- +'</div>'
- );
- newInput.appendTo('#input_container');
- $('#input').val('');
- }else{
- alert("Please enter something");
- }
- });
- $('#submit').on('click', function(){
- var list=[];
- $('.newInput').each(function(){
- list.push($(this).val());
- });
- alert(list.join(', '));
- });
- });
Add new comment
- 187 views