Reputation: 2551
I am using Chosen and I'm dynamically loading options via an AJAX call. Everything works fine but I can't figure out how to change the placeholder text if the result of the AJAX call is empty.
So for example:
<select name="test" multiple="multiple" data-placeholder="Make a selection"
id=MyChosenSel"></select>
When nothing has been selected the box has a placeholder which reads "Make A Selection". I want to have this say "No options available" if the AJAX call returns null
.
I expected this to work:
$('#MyChosenSel').data('placeholder',"No Options").trigger("chosen:updated");
Any ideas?
Upvotes: 6
Views: 3899
Reputation: 7588
In Chosen 1.8.7 (possibly earlier, haven't tested it), the set_default_text
function, called by the chosen:updated
event handler, specifically checks the data-placeholder
attribute, not the jQuery data (which is what .data("placeholder", ...)
sets). So, this is what you have to do:
$("#MyChosenSel")
.attr("data-placeholder", "No Options")
.trigger("chosen:updated");
Upvotes: 1
Reputation: 162
To change the text placeholder for the select you should use the placeholder_text option in the chosen config for example use this:
$("#myChosen").chosen({
placeholder_text:"my custom placeholder text"
});
Upvotes: 3
Reputation: 9995
This answer clarifies how to use jQuery to change the data-placeholder
attribute on the SELECT
tag.
In the code below you can see how to use either jQuery or the plain javascript dataset
attribute of the SELECT
to change the value of chosen select's placeholder.
Note that the key to access placeholder value in the dataset
object is placeholder
(instead of data-placeholder
).
Hope that this benefits anybody.
$('SELECT').chosen({width: '80%'});
$('BUTTON#jQuery').on('click', function() {
$('SELECT').attr('data-placeholder', 'Placeholder updated with jQuery!');
$('SELECT').trigger('chosen:updated');
});
$('BUTTON#dataset').on('click', function() {
$('SELECT')[0].dataset['placeholder'] = 'Placeholder updated with dataset obj!';
$('SELECT').trigger('chosen:updated');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.7.0/chosen.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.7.0/chosen.jquery.js"></script>
<SELECT data-placeholder="Placeholder before chosen:updated">
<OPTION></OPTION>
<OPTION>1</OPTION>
<OPTION>2</OPTION>
</SELECT>
<BUTTON id="jQuery">Click for updating placeholder with jQuery</BUTTON>
<BUTTON id="dataset">Click for updating placeholder with dataset hash</BUTTON>
Upvotes: 0
Reputation: 1552
$("#MyChosenSel").chosen({
allow_single_deselect:true,
disable_search_threshold: 10,
no_results_text: "No options available",
width: "25%"
});
Fiddle here to show you.....http://jsfiddle.net/mikeys4u/99Dkm/237/
Upvotes: 0