Q:

Set a select input of a html form

I try to select a specific select input from a form, where I use select2 library. The documentation writes:

To programmatically select an option/item for a Select2 control, use
  the jQuery .val() method:

$('#mySelect2').val('1'); // Select the option with a value of '1'

So, I try to set the input with the value 0. However, the input isn't changed.. . What I am missing?

$('.js-example-basic-single').select2({
  allowClear: true
});

var myFlag = 0;

$("#haslabel").val(myFlag);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet" />



<div class="row">
  <div class="col-md-12 col-sm-12">
    <form id="form1" class="form-horizontal" role="form">
      <fieldset>
        <div class="form-group">

          <div class="col-sm-12">
            <select class="js-example-basic-single js-states form-control" id="hasLabel" name="hasLabel">
              <option></option>
              <option value="1">yes</option>
              <option value="0">no</option>
            </select>
          </div>
        </div>
      </fieldset>
    </form>
  </div>
</div>

A:

Spell the selector correctly
0 and 1 are false and true - use the strings
val("0") sets the value but does not show it unless you trigger change to see it
Alternatively have the option selected <option value="0" selected>no</option>

Note: to not see ...,  your select has to be wide enough

$(function() {
  $('#hasLabel').select2({allowClear: true});
  $('#hasLabel').val("0").trigger("change"); // set AND show
});
.js-states { width:70px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" />

<div class="row">
  <div class="col-md-12 col-sm-12">
    <form id="form1" class="form-horizontal" role="form">
      <fieldset>
        <div class="form-group">

          <div class="col-sm-12">
            <select class="js-example-basic-single js-states form-control" id="hasLabel" name="hasLabel">
              <option></option>
              <option value="1">yes</option>
              <option value="0">no</option>
            </select>
          </div>
        </div>
      </fieldset>
    </form>
  </div>
</div>

