简体   繁体   中英

Can't overwrite Select2 value with jQuery

I am using select2 in my form, and with jQuery, I am trying to set a default value to it; however whatever I tried didn't work. First, here is my html form:

<div class="form-group>
   <div class="col-xs-12">
      <div class="form-material">
          <label for="item" style="font-size: 14px; margin-bottom: 5px">Name:</label>
          <select id="itemSelect" class="js-select2" name="item" data-placeholder="Select Item..">
               <option></option>
               @foreach ($establishments as $establishment)
                    <option value="{{$item->id}}">{{ $item->name }}</option>
               @endforeach
         </select>         
     </div>
  </div>
</div>

And then, in my jquery, I am trying to write a default value on it.

function somethingClick(id) {
   var theValueToBeSet = jQuery('#item-'+ id).html();  // logs "TestData"

   // First I tried;
   jQuery('#itemSelect').val(theValueToBeSet);

   // Secondly:
   jQuery('#itemSelect').select2('val', theValueToBeSet);

  // Thirdly:
   jQuery('#itemSelect').val(theValueToBeSet).trigger("change")
}

I get no errors in the console. What am I missing/doing wrong?

Check Below code you have to trigger :

 $("#itemSelect").val(theValueToBeSet).trigger("change");

Hope this will help you !!

Below code is working properly :

("#SelectId").select2({
        placeholder: "-Select Options-"
    });
    if ($('#FirstListId').val() != 0) {
        var olddata = $("#SelectId").val();
        $.getJSON('/Home/GetSelectList/' + $('#FirstListId').val(), function (data) {
            var items;
            $.each(data, function (i, secondList) {
                items += "<option value='" + secondList.Value + "'>" + secondList.Text + "</option>";
            });
            $('#SelectId').html(items);
            $("#SelectId").val(olddata).trigger("change");
        });
    }

I hope this is what you're looking for.

Below is the link for the example to change the value for select.

HTML

<select class="test">
    <option value="">-</option>
    <option value="1">Test 1</option>
    <option value="2">Test 2</option>
    <option value="3">Test 3</option>
</select>

Javascript

$(".test option[value=3]").prop("selected","selected").trigger("change");

https://jsfiddle.net/synz/7yc96mo5/1/

And try change the value. I have to add trigger because of select2 function.

It's a little hard to tell as the variable, parameter and function names here aren't great...

Firstly, it's not clear what the parameter id is representing. I suspect there is html we are not seeing as jQuery('#item-'+ id) is selecting a DOM element that has the id of '#item-'+ id , which I cannot find in your example.

Secondly, presuming that jQuery('#item-'+ id) is selecting an arbitrary option DOM element from the select, I think you are getting mixed up when using $item.id and $item.name . The variable theValueToBeSet is set to $item.name , however you are later using it to set the value of the select, which is $item.id .

Try amending your js to the following

function somethingClick(id) {
   var theValueToBeSet = jQuery('#item-'+ id).attr('value');  // <- This line changed

   // First I tried;
   jQuery('#itemSelect').val(theValueToBeSet);

   // Secondly:
   jQuery('#itemSelect').select2('val', theValueToBeSet);

  // Thirdly:
   jQuery('#itemSelect').val(theValueToBeSet).trigger("change")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM