简体   繁体   中英

How to change the value of select2 selectbox?

days_of_week = [{id: 0, text: "Monday"},
                {id: 1, text: "Tuesday"},
                {id: 2, text: "Wednesday"},
                {id: 3, text: "Thursday"},
                {id: 4, text: "Friday"},
                {id: 5, text: "Saturday"},
                {id: 6, text: "Sunday"}]


$("#test").select2({
        data: days_of_week
    })


$("#date").datepicker({
        format: "yyyy-mm-dd"

        })


$("#date").datepicker().on("changeDate", function(event) {
        var selected_date = $("#date").val()
        var day_name = moment(selected_date, "YYYY-MM-DD").format("dddd")
        $("#test").val(day_name)

    })

so basically what im trying to do here is select a date from a datepicker get the day name of that date using moment and change the value of the $("#test").select2() to the selected day_name but what ends up happening is the value of $("#test").select2() is changed but it's changed to empty.

like for example. I the default value for select2 was a "Monday" selecting a date the current value of select2 is now empty.

How do we change the value of select2 using jquery?

I've read the other older posts on here. but they don't work.

In this example the value of your select2 selectbox is an ID (0-6). You are trying to set the value to the label of the selectbox. Also you need to manually trigger a "change" event on a select2 box using.... .trigger("change"); as per documentation .

So you have to do something like this:

$("#date").datepicker().on("changeDate", function(event) {
    var selected_date = $("#date").val();
    //var day_name = moment(selected_date, "YYYY-MM-DD").format("dddd");
    var day_index = moment(selected_date, "YYYY-MM-DD").format("d"); //returns day of week 0-6
    $("#test").val(day_index).trigger("change");
})

PS: Your javascript is missing a whole bunch of semicolons

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