Change select value with Select2 Jquery in Blur event

Asked

Viewed 410 times

-1

I’m using the Select2 JQuery to present the selects of a system I’m developing. I have a field that type the ZIP code and select must have its value changed and presented to the user. My script de teste is currently like this:

<input type="text" class="form-control" name="cep" id="cep" >

<select name="estado" data-init-plugin="select2"> <option value="AC">Acre</option> <option value="RR">Roraima</option> <option value="RO" selected>Rondônia</option> </select>

$("#cep"). Blur(Function() {

$('.state option[value="AC"]'). attr({ Selected : "Selected" }); });

The above code "is functional", the value of select is changed in the back but the value that is presented to the user is not changed. I looked in the documentation of Select2, but I could not find the way to change also the value shown.

Another test I did was to change the class select2-selection__rendered which is generated by Select2. It actually worked, but if you have more selects in the form that also use Select2, all selects are changed.

Código alterando a classe rendered da Select2

$('.Select2-selection__rendered'). html('AC'). attr("title", 'AC');

Someone could tell us how to manipulate Select2 for this purpose?

1 answer

0


I did some research and managed to solve the problem. Actually the solution is simple, just set the method select2() in the class or id you want to change the value of option.

The functional prototype script follows:

Form:

<input type="text" class="form-control" name="cep" id="cep" > <select name="state" id="state" data-init-plugin="select2"> <option value="AC">Acre</option> <option value="RR">Roraima</option> <option value="RO" selected>Rondônia</option> </select>

Script:

$("#cep"). Blur(Function() {

$('#state').val('AC').select2();

});

In the example above the method select2() does all the work by changing the selected value presented to the user, as well as the option in question as selected.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.