Change select2 option on click
Asked Answered
S

4

7

I am using the select2 plugin on my select services_dd in my form, I have a link on the page with a class .js-autoselect. On clicking this I want to take the ID of that link tag and change the select2 option depending on the button they clicked.

The <option> value attribute matches the attribute of the id on the link. The code below is successfully changing the value but the select2 is not updating, it still shows the first selection.

$('.js-autoselect').click(function(e){
    e.preventDefault();
    var option = $(e.target).attr('id').trim().toLowerCase(); // option =link1

    $('#services_dd option:selected').val(option);
    alert($('#services_dd option:selected').val()); // this alerts link1 which is correct

});

Does anyone know how to update the select2

Squash answered 21/12, 2012 at 9:24 Comment(1)
You're changing the value of the selected option - not changing the selected option. Get rid of option:selectedStoical
D
19

$("#services_dd").select2("val", option);

See the Programmatic Access section of the documentation: http://ivaynberg.github.com/select2/#documentation

Dorthadorthea answered 21/12, 2012 at 9:27 Comment(0)
A
1

Working example

Based on @scoota269's answer I wrote the following JS Fiddle that shows this working: https://jsfiddle.net/robertmassaioli/ro2279ts/5/

That should be able to help you see how to make this work.

Code

Just in case JS Fiddle is ever shut down:

$(function() {
    var select = $("#the-select");
    select.select2();

    $("#update").click(function() {
        // How to remove a value
        select.find("option[value=1]").remove();
        // How to add a value
        select.append("<option value='5'>Five</option>");
        select.select2();
    });

    $("#select").click(function() {
        // How to select a value
        var current = select.select2("val");
        current = current || [];
        current.push(2);
        select.select2("val", current);
    });
});
Apices answered 6/6, 2015 at 4:37 Comment(0)
H
0
$('#mySelect2').val('US'); // Change the value or make some change to the internal state
$('#mySelect2').trigger('change.select2'); // Notify only Select2 of changes
Harwin answered 13/11, 2021 at 13:16 Comment(1)
Welcome to Stack Overflow. Code without any explanation are rarely helpful. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please edit your question and explain how it answers the specific question being asked. See How to Answer.Abdicate
U
-2

I think you should simply do

$('#services_dd').val(option);
alert($('#services_dd').val());

Otherwise, in your code, you would only change the value attribute of the selected option (instead of the value of the select element).

Uhf answered 21/12, 2012 at 9:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.