How to change placeholder in select2?
Asked Answered
M

9

11

How do I change the data placeholder with select2?

So far I've tried this.

$("#city").select2({placeholder:"foo"});

And this...

$("#city").attr("data-placeholder","bar");

But neither works.

Munificent answered 28/9, 2013 at 3:34 Comment(2)
It should work.. See the fiddle jsfiddle.net/JZQ3Q Please repplicate your issue in this fiddle.Panto
check my answer from here. https://mcmap.net/q/277115/-select2-control-place-holder-dynamically/73230257#73230257Qualify
M
13

I found that if I just set the attr e.g. $("#city").attr('data-placeholder', 'bar'), there is no effect. However, if I set the attr and then call $("#city").select2() with no arguments, then the placeholder updates.

e.g.

$("#city").attr("data-placeholder","bar");
$("#city").select2();
Munificent answered 30/9, 2013 at 4:14 Comment(3)
You could also just update the placeholder via select2 after it's already been instantiated, without changing the element around (e.g. $("#city").select2({ placeholder: "bar" });).Uniplanar
Anyway, (re)applying select2() on the element will also loose any potential option previously set on this element through javascriptPetrozavodsk
Thank you! This is the only one that worked for me -- and was the simplest.Ela
E
7

For other people looking for an attribute solution to avoid changing JS code. I just had to look this up myself for a project, and it seems select2 just needs the attribute data-placeholder="".

<select id="city" data-placeholder="my placeholder"></select>

See more here: select2 options reference

Echopraxia answered 30/4, 2015 at 22:50 Comment(2)
Mind telling me why the downvote? I just tried to be helpful and I do not see what I did wrong in this case?Echopraxia
Probably because the question asks how to change the placeholder, not simply set it initiallyDiscompose
A
3

You can also do it like this in the template (html) level. Just be sure to assign a blank (e.g. "") string on your first tag.

<select id="city" data-placeholder="Select Anything">
  <option value=""></option>
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
</select>

or we can simply add a data attribute for placeholder via javascript and it should happen before select2 gets initialized.

$('#city').data('placeholder','This is a placeholder');

DEMO

Alemannic answered 19/12, 2016 at 4:52 Comment(0)
P
3

A bit more of a hack-y solution, but one that doesn't involve re-initiating the entire select element is to add the following extensions:

$.fn.getSelect2Placeholder = function () {
    var $select2Container = $(this).data('select2').$container;
    return $select2Container.find('.select2-selection__placeholder').text();
};
$.fn.setSelect2Placeholder = function (placeholder) {
    var $select2Container = $(this).data('select2').$container;
    return $select2Container.find('.select2-selection__placeholder').text(placeholder);
};

This allows for updating the placeholder by simply writing:

$('#the-id-of-your-select2-element').setSelect2Placeholder("Your placeholder text.");

Source

Pileum answered 19/5, 2020 at 11:0 Comment(3)
I found this useful, the only thing is if data is already selected then the getSelect2Placeholder() function will not be able to retrieve the placeholder value.Discompose
Also, if a value is selected, you would need to $('#the-id').empty().setSelect2Placeholder('Placeholder text');, as .empty() is needed to make the placeholder appear so that it can be modified.Discompose
For multi-select, I had to use $select2Container.find('.select2-search__field') instead, and if I used .empty() I then had to use a small delay before setting the placeholder value, otherwise it would reset back to the original.Discompose
U
2

A more direct way ..

$('#select2-' + $id + '-container').find('.select2-selection__placeholder').text('Your Text');

where $id is the id of the select element

Unseemly answered 13/7, 2018 at 12:54 Comment(0)
S
1

Put it in the html that your locator uses like this:

<select id="city" placeholder="my placeholder"></select>
Strop answered 7/2, 2014 at 16:27 Comment(1)
Change to data-placeholder and it works with select2. <select id="city" data-placeholder="my placeholder"></select>Echopraxia
D
1

Several of the given answers have potential issues:

  • The answer by BillRobertson42 works, but it deletes any other configuration options that were previously set on the select2 instance, as does the answer by wdonayredroid

  • The answer by dearsina does not require re-initializing select2 and therefore will not remove any existing configuration options, but it only works on single selects and not multiple selects. I added a comment to that answer on how to make it work for multiple selects, but even in that case, it only works the first time, and re-calling the function requires inserting a short delay. This is also true of the answer by ken-kin.

    Another issue with these answers is that they rely on specific HTML that could be broken by future select2 updates.

I previously had to come up with a solution to update select2 data without rebuilding the control. That solution could work here as well, however I created a simpler solution that allows you to generically update any number of configuration options, and it works for one or all select2 instances that match the given selector.

The first function finds all matching selectors, then calls the second function. This function saves the existing and selected data options, as well as the existing configuration. It then empties, destroys, and rebuilds the select2 instance. Finally, it re-selects any data options that were already selected. See here:

// update configuration options for all matching select2 instances
function select2UpdateConfig(selector, updatedConfigOptions = {}) {
  // loop through all instances of the matching selector and update each instance
  $(selector).each(function() {
    select2InstanceUpdateConfig($(this), updatedConfigOptions);
  });
}

// override configuration options for a single select2 instance
function select2InstanceUpdateConfig(instance, updatedConfigOptions = {}) {
  // make sure this instance has select2 initialized
  // @link https://select2.org/programmatic-control/methods#checking-if-the-plugin-is-initialized
  if (!instance.hasClass('select2-hidden-accessible')) {
    return;
  }

  // get existing configuration options and the currently-selected data
  const existingConfigOptions = JSON.parse(
    JSON.stringify(instance.data('select2').options.options)
  );
  const existingSelected = instance.val();

  // set configuration options with overrides
  const options = Object.assign({}, existingConfigOptions, updatedConfigOptions);

  // empty the select and destroy the existing select2 instance,
  // then re-initialize the select2 instance with the given options
  instance.empty().select2('destroy').select2(options);

  // re-select any options that were selected
  instance.val(existingSelected).trigger('change');
}

The benefit of these functions are that they work generically to update any configuration option, not just the placeholder. They do not require hacking HTML. Select2 listeners should still work after calling the functions. The only caveat is that this may not copy over any custom adapters/callbacks. For most uses cases these generic functions should work.

Discompose answered 12/4, 2024 at 19:29 Comment(2)
I asked this question 10 years ago, and I'm really curious to know. Is this issue is something that people still encounter? If so, did the development of select2 just die off or did the authors ignore the problem? And also, was nothing better developed as a replacement for select2 since then?Munificent
I'm working off select2 version 4.0.13 that has the issue, and have not checked version 4.1.0. It appears development still takes place on the repo. I should update to the latest version to see if it is still an issue.Discompose
S
0

For select2 version 4 I specified the placeholder text in js init code and then update it using $select.select2{placeholder:"updated text..."}

Sydel answered 2/9, 2015 at 11:26 Comment(0)
F
0

The following script can be used:

$("#city").attr('placeholder', 'your text here' );
Fronia answered 4/1, 2021 at 18:39 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.