Welcome folks today in this post we will be building a select option list dropdown generator in javascript
. We will be generating html source code. All the source code of the application is given below.
Get Started
In order to get started we need to make a index.html
file and copy paste the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
<!DOCTYPE html> <html> <head> <title>Select Option List DropDown Generator</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" /> </head> <body> <div class="container"> <h1 class="text-center">Select Option DropDown List Generator</h1> <form id="form"> <div class="form-group"> <label for="options">Options (One Per Line)</label> <textarea name="" class="form-control" id="options" cols="30" rows="10" required placeholder="Enter Options"></textarea> </div> <div class="form-group"> <button class="btn btn-danger btn-block"> Generate Select List </button> </div> </form> <div id="preview"></div> <h2 class="text-center">Source Code</h2> <div class="form-group"> <label for="output">Output HTML:</label> <textarea class="form-control" rows="10" cols="30" id="result" placeholder="Output HTML Code"></textarea> </div> </div> </body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> var result=`` $("#form").submit(function(e){ e.preventDefault() var options = $('#options').val().split('\n'); result+= ` <div class="form-group"> <label for="sel1">Select list:</label> <select class="form-control" id="sel1"> ` options.forEach(option => { result+= `<option>${option}</option>` }); result+=` </select> </div> ` $("#preview").html(result) $("#result").val(format(result.trim())) }) function format(html) { var tab = '\t'; var result = ''; var indent= ''; html.split(/>\s*</).forEach(function(element) { if (element.match( /^\/\w/ )) { indent = indent.substring(tab.length); } result += indent + '<' + element + '>\r\n'; if (element.match( /^<?\w[^>]*[^\/]$/ ) && !element.startsWith("input") ) { indent += tab; } }); return result.substring(1, result.length-3); } </script> </html> |
Screenshot