AlanRubinoff
AlanRubinoff

Reputation: 385

How do i change default option in select Jquery

I have this select, where i load a bunch of countries. After the user selects one, he will go to another page where he searches for information. If he selected a country before he should have that country selected by default (on another select, in another page, which contains the same countries).

<div data-role="fieldcontain">
    <label for="selecionarPaisPreferencia" class="select">Pais</label>
    <select name="selecionarPaisPreferencia" id="SlSelecionarPaisPreferencia"></select>
</div>

How do i change the default option in a select, before loading the page.

BTW: i have already stored the name of the country he selected in a global variable.

i load the options dinamically since im not using database this is for an exercise.

for (i = 0; i < countrys.length; i++) {
    $("#SLSelectPaisConsulta").append('<option data-pais="' + countrys[i] + '">' + countrys[i] + '</option>');
    $("#SlSelecionarPaisPreferencia").append('<option data-pais="' + countrys[i] + '">' + countrys[i] + '</option>');
}

Upvotes: 2

Views: 1081

Answers (3)

Marcovecchio
Marcovecchio

Reputation: 1332

Here goes another way to do it, if you have the value to be selected in SelectedValue:

$("#SlSelecionarPaisPreferencia").find('[value="'+SelectedValue+'"]').attr("selected", true);

For the sake of completeness, it's important to note that using val() directly should be more efficient, but val() won't work with multiple choice selects, while this method will work in single or multiple choice selects. You just have to call it one time for each value you want to select.

Upvotes: 0

DarkAjax
DarkAjax

Reputation: 16223

You could try:

$("#SlSelecionarPaisPreferencia").val(selectedPais);

Or

$("#SlSelecionarPaisPreferencia")
    .children(':contains('+selectedPais+')').prop('selected',true);

Or:

$("#SlSelecionarPaisPreferencia > option:contains("+selectedPais+")").prop('selected',true);

Upvotes: 0

Nadh
Nadh

Reputation: 7243

$('#selecionarPaisPreferencia').val('country_name_value_here');

Upvotes: 1

Related Questions