Search code examples
javascriptjqueryasp.net-core-mvcjquery-select2

JQuery Select2 dropdown not able to set the text in MVC


I am using the select2 jquery plugin. I was unable to set/assign the text to the select control. I used select2 with trigger function for setting the value. Firstly the control which I have taken is helper class dropdown @Html.DropDownList in MVC. I am getting the error like Cannot read properties of undefined (reading 'text'). My code is like as follows :

Index.cshtml:

@Html.DropDownList("ddl", ViewBag.classFieldList as SelectList, "Select class", new { @id = "ddl", @class = "form-control", @name = "ddl", @onchange = "Checkclassvalu(this)" })

<Script>
$(document).ready(function () {

$('#ddl').select2({
           // closeOnSelect: false,
 });


var ddlclassvalue = 'seventh';

alert('class is : ' + ddlclassvalue);
var optionValue = $("#ddl option:contains('" + ddlclassvalue + "')").val();
$("#ddl").select2("val", optionValue).trigger('change');

});
</script>

And the error which I am getting is : Cannot read properties of undefined (reading 'text')

Error Image


Solution

  • unable to set/assign the text to the select control

    This is what I found from select2 webiste.

    $('#mySelect2').val('1'); // Select the option with a value of '1'
    $('#mySelect2').trigger('change'); // Notify any JS components that the value changed
    

    enter image description here

    And it worked in my side in an asp.net core mvc application. Like what you can see in codes and screenshot below, by default location2 is seleted and using codes to make it select location3

    @Html.DropDownList("ddl", ViewBag.classFieldList as SelectList, "Select class", new { @id = "ddl", @class = "form-control", @name = "ddl" })
    
    @section Scripts{
        <script>
            $(document).ready(function () {
    
                $('#ddl').select2({
                    // closeOnSelect: false,
                });
    
                var ddlclassvalue = 'localtion3';
                var optionValue = $("#ddl option:contains('" + ddlclassvalue + "')").val();
                alert(optionValue);
                $("#ddl").val(optionValue);
                $('#ddl').trigger('change');
            });
        </script>
    }
    

    enter image description here enter image description here