Selected to update placeholder text when dynamically populating options
I am using Chosen and I am loading parameters dynamically 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 is selected, there is a placeholder in the field that reads "Make a selection." I want to say that "No parameters available" if the AJAX call returns null
.
I expected this to work:
$('#MyChosenSel').data('placeholder',"No Options").trigger("chosen:updated");
Any ideas?
source to share
$("#MyChosenSel").chosen({
allow_single_deselect:true,
disable_search_threshold: 10,
no_results_text: "No options available",
width: "25%"
});
Try it here to show you ..... http://jsfiddle.net/mikeys4u/99Dkm/237/
source to share
This answer clarifies how to use jQuery to change an attribute data-placeholder
on a tag SELECT
.
In the code below, you can see how to use jQuery or a simple javascript dataset
attribute SELECT
to change the value of the selected selected placeholder.
Note that the key to access the padding value in the object dataset
is placeholder
(instead of data-placeholder
).
Hope it benefits anyone.
$('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>
source to share
In Chosen 1.8.7 (maybe not previously tested), the function called by the event handler specifically validates the attribute , not the jQuery data (that is, what sets). So, here's what you need to do: set_default_text
set_default_text
chosen:updated
data-placeholder
.data("placeholder",...)
$("#MyChosenSel")
.attr("data-placeholder", "No Options")
.trigger("chosen:updated");
source to share