0

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.

Dirk J. Faber
  • 4,360
  • 5
  • 20
  • 58

1 Answers1

1

You just add the following code into noCity is checked event. I run test and it's OK :))

$("#location").select2().val("0").trigger("change");
Tomato32
  • 2,145
  • 1
  • 10
  • 10
  • Thank you for your suggestion. I did what you said as `if ($('#noCity').is(':checked')) { $("#location").select2().val("0").trigger("change");`, but nothing really changes. Could you tell me what I do wrong? – Dirk J. Faber Jul 25 '18 at 21:18
  • Wait, I got it, it was in the wrong event. It's all working now, thank you! – Dirk J. Faber Jul 25 '18 at 21:25