I have a field that works with Select2 called location
, where a user can enter one or more locations. Then I have a checkbox noCity
which can be checked by the user if there is no location
.
What I try to archieve: when noCity
is checked, location
is disabled, the placeholder removed, and all values cleared.
What I have archieved: when noCity
is checked, location
is disabled, when unchecked, enabled and when the form is loaded and noCity
was checked, disabling is done correctly as well.
My issue: I cannot seem to remove the values of the field location
, nor the placeholder. .attr("placeholder", '', this)
and .val('', this)
do not seem to work and other tryouts have failed.
My code so far:
$('#location').select2({
placeholder: 'Enter a city'
});
$("#noCity").click(function () {
if (jQuery(this).prop("checked")) {
jQuery("#location")
.prop("disabled", this)
.attr("placeholder", '', this)
.val('', this)
;
} else {
jQuery("#location")
.prop("disabled", false)
.attr("placeholder", 'Enter the name of the city')
.val('')
;
}
});
if ($('#noCity').is(':checked')) {
jQuery('#location')
.prop('disabled', this)
.attr('placeholder', '')
.val('');
}
and html:
Location: <select id="location" multiple="multiple" style="width: 300px">
<option>New York</option>
<option>Hong Kong</option>
<option>Amsterdam</option>
</select>
<br>
<label>No city:<input id="noCity" type="checkbox"></label>
Here is a JSFiddle
My question: how can I make sure that when noCity
is checked, location
is disabled, the placeholder removed, and all values cleared (while also when noCity
is unchecked the field location
is enabled again and the placeholder back)?
Edit: my question is similar to this one, however I try to implement this when a checkbox is unchecked (which still not works) and I use Select2 version 4 which works differently.