Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html>
- <head>
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/css/bootstrap-select.min.css">
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/js/bootstrap-select.min.js"></script>
- </head>
- <body>
- <select class="selectpicker" id="dynamicSelect" data-live-search="true">
- <!-- Initial options if any -->
- <option value="1">Option 1</option>
- <option value="2">Option 2</option>
- </select>
- <script>
- $(document).ready(function() {
- // Initialize the selectpicker with a custom no results message
- $('#dynamicSelect').selectpicker({
- noneResultsText: 'No results matched "{0}"'
- });
- // Function to add a new option to the selectpicker
- function addOptionToSelectpicker(value, text) {
- var newOption = $('<option>', {
- value: value,
- text: text
- });
- $('#dynamicSelect').append(newOption).selectpicker('refresh');
- }
- // Function to handle the input and enter key logic
- function handleSelectpickerInput(event) {
- var searchValue = $(event.target).val().toLowerCase();
- var optionExists = false;
- if (event.key === "Enter" && searchValue.trim() !== '') {
- // Check if the option already exists
- $('#dynamicSelect option').each(function() {
- if ($(this).text().toLowerCase() === searchValue) {
- optionExists = true;
- $('#dynamicSelect').selectpicker('val', $(this).val());
- $('#dynamicSelect').selectpicker('refresh');
- return false; // Break the loop
- }
- });
- // If the option does not exist, add it
- if (!optionExists) {
- var newOptionValue = searchValue;
- var newOptionText = searchValue.charAt(0).toUpperCase() + searchValue.slice(1);
- addOptionToSelectpicker(newOptionValue, newOptionText);
- $('#dynamicSelect').selectpicker('val', newOptionValue);
- $('#dynamicSelect').selectpicker('refresh');
- }
- // Clear the input field
- $(event.target).val('');
- }
- }
- // Event listener for the input field of the selectpicker
- $('.bs-searchbox input').on('keyup', function(event) {
- var searchValue = $(this).val();
- var noneResultsText = 'Press Enter to add "' + searchValue + '"';
- $('#dynamicSelect').data('selectpicker').options.noneResultsText = noneResultsText;
- $('#dynamicSelect').selectpicker('render');
- handleSelectpickerInput(event);
- });
- });
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement