Input Select using Select2 Plugin
Submitted by nurhodelta_17 on Wednesday, May 16, 2018 - 20:04.
Adding Dependencies
In order to add select2, we need to include the plugin to our page. Note that files use in this tutorial is included in the downloadable. Include the CSS and JS of select2 in the header section of your page of the JS file before the closing body tag.
Don't forget to include jQuery as well.
Initializing Select2
Next step is to initialize our select2 and assign it to a class.- $(function(){
- //Initialize Select2 Elements
- $('.select2').select2()
- });
Creating the Select Input
Lastly, we create the select tag where we want to apply select2.Full HTML
Here's the full html.- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>Input Select using Select2 Plugin</title>
- <link rel="stylesheet" type="text/css" href="bootstrap4/css/bootstrap.min.css">
- <link rel="stylesheet" type="text/css" href="assets/select2.min.css">
- </head>
- <body>
- <div class="container">
- <h1 class="text-center" style="margin-top:30px;">Input Select using Select2 Plugin</h1>
- <hr>
- <div class="row justify-content-center">
- <div class="col-sm-4">
- <?php
- $fruit = $_POST['fruit'];
- echo "<p>You selected: <b>".$fruit."</b></p>";
- }
- ?>
- <form method="POST">
- <div class="form-group">
- <select class="form-control select2" name="fruit">
- <option value="" selected>- Select Fruit -</option>
- <option>Apple</option>
- <option>Orange</option>
- <option>Strawberry</option>
- <option>Mango</option>
- <option>Watermelon</option>
- <option>Melon</option>
- <option>Jackfruit</option>
- <option>Star Apple</option>
- <option>Buko</option>
- <option>Guava</option>
- <option>Peach</option>
- <option>Pears</option>
- <option>Chico</option>
- <option>Durian</option>
- </select>
- </div>
- <button type="submit" class="btn btn-primary" name="submit">Submit</button>
- </form>
- </div>
- </div>
- </div>
- <script src="assets/jquery.min.js"></script>
- <script src="assets/select2.full.min.js"></script>
- <script>
- $(function(){
- //Initialize Select2 Elements
- $('.select2').select2()
- });
- </script>
- </body>
- </html>
Add new comment
- 382 views