Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Option adding (with custom callback) #166

Open
wants to merge 9 commits into
base: master
Choose a base branch
from

Conversation

koenpunt
Copy link
Collaborator

Option adding

You can specify a create_option option, which can be a boolean or callback function.

Example for allowing adding of new items:

$(function() {
  $(".chzn-select").chosen({
    create_option: true,
    // persistent_create_option decides if you can add any term, even if part
    // of the term is also found, or only unique, not overlapping terms
    persistent_create_option: true,
    // with the skip_no_results option you can disable the 'No results match..' 
    // message, which is somewhat redundant when option adding is enabled
    skip_no_results: true
  });
});

Or with a callback and an AJAX request to, for example, save the terms in your database:

$(function() {
  $(".chzn-select").chosen({
    create_option: function(term){
      var chosen = this;
      $.post('add_term.php', {term: term}, function(data){
        chosen.append_option({
          value: 'value-' + data.term,
          text: data.term
        });
      });
    }
  });
});

Custom text

Through the options it is also possible to customize the text used in the 'Add option' link, like so:

$(function() {
  $(".chzn-select").chosen({
    create_option_text: 'Create category'
  });
});

I'll try to keep my release up to date with harvesthq/master: https://github.com/koenpunt/chosen/releases

@marcusjames
Copy link

This is great! Would it be easy to make it so hitting the enter key also triggers the "add item" so you don't have to click the link? The enter key already works for selecting existing items from the list. Thanks!

@koenpunt
Copy link
Collaborator Author

koenpunt commented Aug 8, 2011

That was in my case intentionally left out, so the user is really aware of adding new items. But maybe I will add it as an extra option.

@zanematthew
Copy link

Any desire to bundle this with the jquery plugin?

@bewest
Copy link

bewest commented Dec 19, 2011

I believe this is a good candidate for solving issue #5.

@koenpunt
Copy link
Collaborator Author

I also fixed some small things, and updated my first comment here with the correct usage examples.

Also the functionality in the prototype version now matches with the jquery version again.

@edrex
Copy link

edrex commented Dec 26, 2011

+1 on UI
+1 on code review

I'm using this branch on a site, hope it gets merged soon.

@matheo
Copy link

matheo commented Mar 13, 2012

@harvesthq There's any idea if this will be merged?

I'm a third party developer of the Zikula Web Application Framework, and we're interested to include Chosen on the bundled libraries, but this feature is very useful and seems that there's no attention to this pull request.

Personally, I'm using @koenpunt's master branch because it does what I need at this moment, but will anybody review the quality of this PR (I can't because my JS skills are low) and include this in the main project?

This is a feature requested months ago by a ot of people, and would be good to know if someone will take care of this,
or if end-users will have to choose between the main project or koenpunt's fork.

Thanks for the great job.

@sontek
Copy link

sontek commented Mar 15, 2012

Is this going to be merged in? I need to dynamically create items in the list.

@bewest
Copy link

bewest commented Mar 17, 2012

@matheo I performed a code review on several branches solving issue #5 and recommended this one, FWIW.

@sontek
Copy link

sontek commented Mar 19, 2012

If this isn't a good patch that could be merged, just let me know why and I will make the changes needed, I really want this feature put into chosen.

@danbronsema
Copy link

+1 For getting this merged in.
Would also be good to have option for enter key to triggers the "add item"

@amacneil
Copy link

This would be really helpful. Please merge!

@edrex edrex mentioned this pull request Apr 12, 2012
@ixti
Copy link

ixti commented Apr 25, 2012

This is really awesome feature, that chosen lack of.

@willdurand
Copy link

👍

@mikke123
Copy link

+1 for merging this into master

@gabrielbull
Copy link

Wants this as well

@kyriacos
Copy link

+1

1 similar comment
@timoxley
Copy link

+1

@radomirml
Copy link

+!

@JCKodel
Copy link

JCKodel commented May 7, 2012

There is a bug when a OnChange event is present for the tag. When creating a new option, the OnChange event must be triggered, because the selection was changed Chosen.prototype.select_append_option = function (options) { var option; option = $('<option />', options).attr('selected', 'selected'); this.form_field_jq.append(option); this.form_field_jq.trigger("liszt:updated"); this.form_field_jq.trigger("change"); // ADD THIS LINE TO FIRE THE CHANGE EVENT return this.search_field.trigger('focus'); }; I needed the OnChange event to enable the submit button when a item is available in the chosen autocomplete (there was none, and I added one with the new create_option config)

@a-bastin
Copy link

+1 ! Great feature !

@tute
Copy link

tute commented May 16, 2012

+1

2 similar comments
@oisinlavery
Copy link

+1

@abrambailey
Copy link

+1

@pedro380085
Copy link

Still not merged?

@TylerRick
Copy link

Just came across this as well... Without this feature, I would have to use select2 instead...

@cashlalala
Copy link

+1 never forget!

@dcangulo
Copy link

Why isn't this merged?

@prohtex
Copy link

prohtex commented Nov 2, 2018

Does anybody know the callback function for removing a newly added option? I thought it was create_option_clear but that isn't working for me...

@pangdaxing23
Copy link

This would be a great feature, please merge this.

MadisonHere pushed a commit to MadisonHere/ActivateHubOrig that referenced this pull request Apr 3, 2019
@joshm1204
Copy link

What is the status of this feature? Would like it merged

@mcarpenterjr
Copy link

The general public feedback on this looks mostly positive, yet it's been hanging around for almost 7/8 years. Is there a specific reason Harvest doesn't want this merged?

@hrshtmims
Copy link

I believe they are dead.

Amorymeltzer added a commit to Amorymeltzer/twinkle that referenced this pull request Jan 21, 2020
- Move partial field to block options, better place
- Select partial block template and hide article if partial (MA smart as fuck, use pageparam and reasonparam)
- add hidden partial to field (helps build query and preview)
- Build rest of query
- Add defaultToPartialBlocks preference option
- Only show tooltip if partial
- Add checks for no talk editing and noemail/nocreate
- Don't disable partial block button, can add pblock template
- Better previous block log message
- Use a global variable for formatted namespace.  Empty string no good; Morebits.wikipedia.namespacesFriendly previously handled this, removed in wikimedia-gadgets#600

Use select2

This system needs multiple user inputs, which can't be done nicely with chosen (See harvesthq/chosen#166).  Can use select2's tags system.

Can't stop multiselect from showing dropdown:

- the empty string is awful
- minimumResultsForSearch: -1 doesn't work, nor does infinity
- dropdownCss and dropdownCssClass require the full version (https://stackoverflow.com/a/22138303/2521092)
- css stuff applies to both(?) absent the above
- dropdownParent: $form.find('[name=pagerestrictions]') weirdly works (puts it somewhere invisible?) but breaks scrolling without a visual cue
Amorymeltzer added a commit to Amorymeltzer/twinkle that referenced this pull request Jan 21, 2020
Closes wikimedia-gadgets#802.

- Move partial field to block options, better place
- Select partial block template and hide article if partial (MA smart as fuck, use pageparam and reasonparam)
- add hidden partial to field (helps build query and preview)
- Build rest of query
- Add defaultToPartialBlocks preference option
- Only show tooltip if partial
- Add checks for no talk editing and noemail/nocreate
- Don't disable partial block button, can add pblock template
- Better previous block log message
- Use a global variable for formatted namespace.  Empty string no good; Morebits.wikipedia.namespacesFriendly previously handled this, removed in wikimedia-gadgets#600

Use select2

This system needs multiple user inputs, which can't be done nicely with chosen (See harvesthq/chosen#166).  Can use select2's tags system.

Can't stop multiselect from showing dropdown:

- the empty string is awful
- minimumResultsForSearch: -1 doesn't work, nor does infinity
- dropdownCss and dropdownCssClass require the full version (https://stackoverflow.com/a/22138303/2521092)
- css stuff applies to both(?) absent the above
- dropdownParent: $form.find('[name=pagerestrictions]') weirdly works (puts it somewhere invisible?) but breaks scrolling without a visual cue
Amorymeltzer added a commit to Amorymeltzer/twinkle that referenced this pull request Jan 21, 2020
Closes wikimedia-gadgets#802.

- Move partial field to block options, better place
- Select partial block template and hide article if partial (MA smart as fuck, use pageparam and reasonparam)
- add hidden partial to field (helps build query and preview)
- Build rest of query
- Add defaultToPartialBlocks preference option
- Only show tooltip if partial
- Add checks for no talk editing and noemail/nocreate
- Don't disable partial block button, can add pblock template
- Better previous block log message
- Use a global variable for formatted namespace.  Empty string no good; Morebits.wikipedia.namespacesFriendly previously handled this, removed in wikimedia-gadgets#600

Use select2

This system needs multiple user inputs, which can't be done nicely with chosen (See harvesthq/chosen#166).  Can use select2's tags system.

Can't stop multiselect from showing dropdown:

- the empty string is awful
- minimumResultsForSearch: -1 doesn't work, nor does infinity
- dropdownCss and dropdownCssClass require the full version (https://stackoverflow.com/a/22138303/2521092)
- css stuff applies to both(?) absent the above
- dropdownParent: $form.find('[name=pagerestrictions]') weirdly works (puts it somewhere invisible?) but breaks scrolling without a visual cue
Amorymeltzer added a commit to Amorymeltzer/twinkle that referenced this pull request Jan 22, 2020
Closes wikimedia-gadgets#802.

- Move partial field to block options, better place
- Select partial block template and hide article if partial (MA smart as fuck, use pageparam and reasonparam)
- add hidden partial to field (helps build query and preview)
- Build rest of query
- Add defaultToPartialBlocks preference option
- Only show tooltip if partial
- Add checks for no talk editing and noemail/nocreate
- Don't disable partial block button, can add pblock template
- Better previous block log message
- Use a global variable for formatted namespace.  Empty string no good; Morebits.wikipedia.namespacesFriendly previously handled this, removed in wikimedia-gadgets#600

Use select2

This system needs multiple user inputs, which can't be done nicely with chosen (See harvesthq/chosen#166).  Can use select2's tags system.

Can't stop multiselect from showing dropdown:

- the empty string is awful
- minimumResultsForSearch: -1 doesn't work, nor does infinity
- dropdownCss and dropdownCssClass require the full version (https://stackoverflow.com/a/22138303/2521092)
- css stuff applies to both(?) absent the above
- dropdownParent: $form.find('[name=pagerestrictions]') weirdly works (puts it somewhere invisible?) but breaks scrolling without a visual cue
Amorymeltzer added a commit to Amorymeltzer/twinkle that referenced this pull request Jan 22, 2020
Closes wikimedia-gadgets#802.

- Move partial field to block options, better place
- Select partial block template and hide article if partial (MA smart as fuck, use pageparam and reasonparam)
- add hidden partial to field (helps build query and preview)
- Build rest of query
- Add defaultToPartialBlocks preference option
- Only show tooltip if partial
- Add checks for no talk editing and noemail/nocreate
- Don't disable partial block button, can add pblock template
- Better previous block log message
- Use a global variable for formatted namespace.  Empty string no good; Morebits.wikipedia.namespacesFriendly previously handled this, removed in wikimedia-gadgets#600

Use select2

This system needs multiple user inputs, which can't be done nicely with chosen (See harvesthq/chosen#166).  Can use select2's tags system.

Can't stop multiselect from showing dropdown:

- the empty string is awful
- minimumResultsForSearch: -1 doesn't work, nor does infinity
- dropdownCss and dropdownCssClass require the full version (https://stackoverflow.com/a/22138303/2521092)
- css stuff applies to both(?) absent the above
- dropdownParent: $form.find('[name=pagerestrictions]') weirdly works (puts it somewhere invisible?) but breaks scrolling without a visual cue
Amorymeltzer added a commit to Amorymeltzer/twinkle that referenced this pull request Jan 22, 2020
Closes wikimedia-gadgets#802.

- Move partial field to block options, better place
- Select partial block template and hide article if partial (MA smart as fuck, use pageparam and reasonparam)
- add hidden partial to field (helps build query and preview)
- Build rest of query
- Add defaultToPartialBlocks preference option
- Only show tooltip if partial
- Add checks for no talk editing and noemail/nocreate
- Don't disable partial block button, can add pblock template
- Better previous block log message
- Use a global variable for formatted namespace.  Empty string no good; Morebits.wikipedia.namespacesFriendly previously handled this, removed in wikimedia-gadgets#600

Use select2

This system needs multiple user inputs, which can't be done nicely with chosen (See harvesthq/chosen#166).  Can use select2's tags system.
Amorymeltzer added a commit to Amorymeltzer/twinkle that referenced this pull request Jan 24, 2020
Partial blocks (https://phabricator.wikimedia.org/T190350) were turned on following an RfC (https://en.wikipedia.org/wiki/Wikipedia:Requests_for_comment/Partial_blocks), so it's time to support them.  Done so by adding a checkbox that toggles a "partial" status for both the blocking and templating behaviors.

In order to support entering specific pages, the modules needs to support multiple custom user inputs, which can't be done nicely with chosen (See harvesthq/chosen#166).  We can, however, use select2's tags system, recently added in wikimedia-gadgets#812 to make wikimedia-gadgets#692 (warn/xfd) happen.

This is all an active WIP, including the policy (WP:PB) and the/any templates (right now, only {{uw-pblock}}) so a lot of this is likely to be in flux for a while.

Some stray notes:

- Adds a `defaultToPartialBlocks` preference option
- Makes use of a hidden partial item to help build the query (like `reblock`)
- Includes checks to prevent empty entries (T208645])
- Adds jumping boxes for `email`/`accountcreate` when just issuing a partial template
- Will ignore the `email`/`accountcreate` template parameters if there's an `area`
- CSS and select2 tweaks a la wikimedia-gadgets#692
- I've skipped proper processing in `saveFieldset` of the select2 menu items, it's easier to just do `.join('|')` for the query
- This use a variable for formatted namespaces, namely "(Article)" rather than "".  The empty string really is no good here; Morebits.wikipedia.namespacesFriendly previously handled this sort of thing, was removed in wikimedia-gadgets#600.
- Compared to the rest of Twinkle, this is a weird module!  Very different but pretty enjoyable all in all; @MusikAnimal built something really quite elegant here in wikimedia-gadgets#260.

Closes wikimedia-gadgets#802.
@JJJ JJJ mentioned this pull request Jul 23, 2020
@dangbert
Copy link

dangbert commented Sep 14, 2020

FYI if you don't want to download a fork of this library, this is a hacky workaround I did instead:
(note that "search-select" is the ID of my select element)

// https://harvesthq.github.io/chosen/options.html#triggered-events
// add a button to dropdown for users to use custom search strings
$("#search-select").on("chosen:no_results", function(evt, params) {
  let elem = $("#search-select").siblings(".chosen-container").find(".chosen-choices .search-field:last input");
  let text = elem.val().replace(/'/g, ""); // get search string user typed and remove all single quote characters
  text = `<button class="btn btn-success" onClick="addCustom('${text}')" style="height: 20px; font-size: 13px; padding: 1px 4px 1px 4px;">Use custom '${text}'</button>`;
  $("#search-select").siblings(".chosen-container").find(".no-results").html(text);
});

// add's a custom search string option to the dropdown (and selects it)
function addCustom(searchStr) {
  let arr = $("#search-select").val();
  $("#search-select").html($("#search-select").html() + "<option value='" + searchStr + "'>" + searchStr + "</option>");
  $("#search-select").val(arr.concat([searchStr])); // append to existing selected options
  $("#search-select").trigger("chosen:updated");
}

Here's what it looks like:
(note that I'm using bootstrap classes to style my button so yours may look different):
out2

Another alternative, is to simply use the browser's native support for datalists

@z1ad
Copy link

z1ad commented Aug 11, 2021

Thanks @dangbert for sharing your solution - Ive made some minor tweaks to the UI and made it work with symbols/html.

// from: https://github.com/harvesthq/chosen/pull/166#issuecomment-692317968
$("select[multiple]").on("chosen:no_results", function() {
    var select = $(this);
    let search = select.siblings(".chosen-container").find(".chosen-choices .search-field:last input");
    let text = escapeHTML(search.val());
    // dont add if it already exists
    if (! select.find('option[value=' + escapeSelector(search.val()) + ']').length) {
        var btn = $('<li class="active-result highlighted">' + text + '</li>');
        btn.on("mousedown mouseup click", function(e) {
            let arr = select.val();
            select.html(select.html() + "<option value='" + text + "'>" + text + "</option>");
            select.val(arr.concat([text]));
            select.trigger("chosen:updated");
            search.focus();
            e.stopImmediatePropagation();
            return false;
        });
        search.on("keydown", function(e) {
            if (e.which == 13) {
                btn.click();
                return false;
            }
        });
        select.siblings(".chosen-container").find(".no-results").replaceWith(btn);
    } else {
        select.siblings(".chosen-container").find(".no-results").replaceWith('');
    }
}).on("change", function(e, params) {
    var select = $(this);
    if (params.deselected) {
        select.find('option[value=' + escapeSelector(params.deselected) + ']').first().remove();
        select.trigger("chosen:updated");
    }
});
function escapeHTML(html) {
    return html
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}
// from: https://stackoverflow.com/questions/739695/jquery-selector-value-escaping
function escapeSelector(string) {
    return string.replace(/([ !"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~])/g,'\\$1');
}

@paytah232
Copy link

@z1ad Is there a way to modify this to work with chosen-select that is NOT a multiselect. My use case is I want to display a list of shelves the user can select from, but also give the option for them to type the name of a new shelf.

Also +1 for this feature to be merged!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment