Adding new elements to a chosen selection while conducting a search on chosen select

How do I add a new value that is not already selected? I have set the 'no_results_text' to display an <a> tag, and it's working fine.

$('#secondary_diagnosis').chosen({no_results_text: '<a onclick="add_new_diagnosis()">Save as New </a>'});
https://i.sstatic.net/I4lYo.png

This is my current code:

However, when I try to add a new value that is part of the existing values, the 'no_results_text' doesn't show. I need a solution to call my predefined function add_new_diagnosis().

Is there a way to include <a> tags on the chosen-search-input field? https://i.sstatic.net/MumBi.png

Here is the current code snippet:

<select class="col-md-11" name="secondary_diagnosis" id="secondary_diagnosis"
      class="form-control chosen" title="Diagnosis">
          <option value="0">Other</option>
          <option value="0">other retinal</option>
          <option value="0">Couch</option>
          <option value="0">Fever</option>
</select>
window.onload = function () {
        $('#secondary_diagnosis').chosen({no_results_text: '<a onclick="add_new_diagnosis()">Save as New </a>'});
    }

Answer №1

This Data List makes it easy to input events and I've found it to be effective.

<input class="form-control" type="text" list="events" name="event_input" id="event_input" onclick=""/>
<datalist id="events" >
       <option value="0">Meeting</option>
       <option value="0">Presentation</option>
       <option value="0">Training Session</option>
       <option value="0">Conference Call</option>
</datalist>

Answer №2

If you're looking for an alternative to chosenJS, consider giving the select2 jQuery plugin a try.

Here is an example of how you can use it in your HTML:

<select class="form-control" id="select2" multiple="multiple">
  <option selected="selected">orange</option>
  <option>white</option>
  <option selected="selected">purple</option>
</select>

To customize its functionality through JS initialization, you can do the following:

$("#select2").select2({
    tags: true,
    width: '100%',
    tokenSeparators: [',', ' ']
}).on("change", function(e) {

    var isNew = $(this).find('[data-select2-tag="true"]');
    if(isNew.length && $.inArray(isNew.val(), $(this).val()) !== -1){
        $.post('http://example.com/api/tags/add', { tag: isNew.val() }, function(res){
            if(res) {
                isNew.replaceWith('<option selected value="'+res.tag_id+'">'+res.tag+'</option>');
            } else {
                isNew.remove();
            }
        }, 'json');
    }
});

Answer №3

Take a look at the code snippet below.

window.onload = function () {
        $('#secondary_diagnosis').chosen({no_results_text: 'Save as New'});
        
        $('.chosen-container').on('click', '.no-results', function(){
           add_new_diagnosis($(this).find('span').text());
           $('#secondary_diagnosis').val('').trigger('chosen:updated');
        });
        
        function add_new_diagnosis(val) {
            console.log(`Add new diagnosis: ${val}`)
        }
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"></script>
<select class="col-md-11 chosen" name="secondary_diagnosis" id="secondary_diagnosis"
      class="form-control" title="Diagnosis">
          <option value="0">Other</option>
          <option value="0">other retinal</option>
          <option value="0">Couch</option>
          <option value="0">Fever</option>
</select>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Interactive font-awesome icons within an interactive dropdown menu

I am currently facing an issue with using two Fontawesome icons in a clickable dropdown menu. The dropdown menu does not toggle when I click on the icons directly; however, it works when I click on the padding around them. The example provided by W3schools ...

Sort the JSON data by the total number of sessions played and display the top 3 results

I would like to organize my JSON data based on the "totalSessionsPlayed" attribute and then display the top 3 entries in a specified div called "show". If I can figure out how to sort the JSON data (which I am currently unsure about), I believe I will be ...

Learn how to fetch data using JavaScript and store it in an array, then display the data in a Bootstrap card using inner

I am working with a Fetch method that looks like this: async function sendApiRequest() { let APP_ID = "f61bb958"; let APP_Key = "7c465e19d8e2cb3bc8f79e7a6e18961e" let INPUT_VALUE = document.getElementById("inputRecipe&q ...

What is the best way to retrieve a message from a resource file using JavaScript?

I have both English and Japanese resource files. When my website switches to Japanese language, I need the messages to display in Japanese just like they do in English. This will require dynamically displaying messages in JavaScript. Thank you. ...

Creating a dynamic menu in antdesign requires a few simple steps to customize the

I am looking to implement a dynamic menu using antdesign version 4.19.5 Below is the code for a static menu: <Menu selectable selectedKeys={activeKey}> { <Menu.SubMenu title="Main Title 1" > <Menu.Item key={&a ...

Missing Values in jQuery Variable

I'm having trouble with adding a link after a block of text. Although the links render fine, the href tag seems to disappear. var eventstuff = data.text; var eventElement = $("<div class='well well-sm eventsWells'>"); var deleteButton ...

Manually load a node.js module from scratch

Is there a way to utilize Node's native "module" module for manually loading in a module from a file instead of relying on the normal require function? I understand this may seem like an unusual request, but I specifically need modules that declare t ...

Add "http://www" to the beginning of data-src using jQuery

I am currently in the process of creating a basic web scraping tool and I want to add URL domain names to the image results. Below is the code that I have written up until now: function pageFunction(context) { var $ = context.jQuery; var results = ...

Create a variety of tables populated with numerous hyperlinks within each table on a webpage

I have a website where I need to display multiple tables with different data, along with appropriate links within the table cells. Plan: Each table on the webpage represents a different school subject, showcasing performance metrics such as SAT scores, fi ...

What is the process for changing a DynamoDB table from PROVISIONED to PAY_PER_REQUEST using Node.js?

Currently, I have a DDB table set up with BillingMode: PROVISIONED and ProvisionedThroughput:{...}. My goal is to switch it to BillingMode: PAY_PER_REQUEST, but every time I attempt this change, I encounter the following error: TypeError: Cannot read prop ...

After the first click, the .css function fails to work on the second click

THE MAIN CONCEPT: I have a collection of 16 blocks (div) and several buttons (a). Each button corresponds to a specific set of blocks. Initially, all the blocks are in the "ON" state. Pressing a button will turn off the related set of blocks, displaying t ...

The link between language and the concept of home is unbreakable

I am currently working on a website located at www.canal.es/wordpress/ Using qtranslate, the code I have implemented for languages is as follows: <div id="language"> <ul> <li><a href="?lang=es" <?php if (qtrans ...

Is there a way to invoke a JavaScript function specifically for a given link?

I am trying to make the JavaScript only apply to a specific A LINK (#tornado,_bar -> ul -> li -> a links) when clicked, but it is applying to all A links. How can I specify the particular link in the JS? The JavaScript code is not functioning cor ...

Tips for organizing data from XML into mongodb

As a JavaScript beginner, I am struggling with uploading an example XML file. I have a JS file that is parsing data to mongo DB. How can I implement sorting in the process while excluding null values from priceService:fullXML.Report.ds[i].i[j]['$&apo ...

Showing information from a database query

Let's say we have a form that submits data to the dataprocess.php file after submission. The dataprocess.php file processes the form variables and outputs the desired results. It can be challenging to directly echo content into a specific div on a pa ...

Having trouble verifying a phone number using the awesome-phonenumber npm package?

I recently developed some JavaScript using the awesome-phonenumber npm package. index.js const yargs = require('yargs'); var PhoneNumber = require( 'awesome-phonenumber' ); const argv = yargs .usage('Usage: $0 -n [num]' ...

Whenever the ajax oncomplete event is triggered, Primefaces overrides the functionality of jquery, leading to

I have implemented a plugin for fixed table columns in my Primefaces project. The plugin is somewhat functional, but I am facing some issues. primefaces v6.1 jQuery v1.7.1 It works under the following conditions; p:dataTable with <p:ajax event="page ...

Tips for modifying object key values in JavascriptLet's explore ways to

Looking to transform my JSON object: "pencil": { "100": { "value": "#00000008", "type": "color" }, "200": { "value": "#0000000d", "type" ...

Ways to switch text on and off smoothly using transitions

I have created a webpage where text starts off hidden but has a visible heading. When you click on the heading, the text is revealed below. I am putting the final touches and aiming to make the text slide in smoothly. I am using Javascript for toggling ins ...

Guide on enabling the scrollbar within a text area while utilizing the pointer-events: none property

After applying the CSS rule pointer-events: none to the text area, I noticed that the scrollbar was disabled. I need the scrollbar to remain enabled so that users can scroll and view the entire content, while still preventing editing within the textarea u ...