I have a database with the users' options, and several of these options are adjusted with selects, and what I need is that when the page loads, the values retrieved from the database are displayed selected.
I have tried with several codes like this and I don't understand why it doesn't work and it doesn't give errors in the console either:
$("#selectLang").prop("selectedIndex", 2);
// También he probado con esto:
$("#selectLang").val('2');
Note: The 2, in my code is
<?php echo $lang_value; ?>
, and from the console it appears that it has been printed correctly.
Example select HTML code:
<div class="form-group">
<label for="inputState">Idioma</label>
<select id="inputState selectLang" class="form-control" name="lang">
<option value="1">Español</option>
<option value="2">English</option>
</select>
</div>
It is possible that .prop
they start counting from 0, but they do not work when the value is 1 either.
Clarifications: The ID is not duplicated, the jQuery code is at the end of the code, and I've tried both with and without quotes. I don't use
selected
because there are too many options and you would have to do oneif
for each one.
The id of your
<select>
has a space. Or you do it like this:Or you just change the id:
Edit: The HTML5 spec doesn't allow space in the id attribute, so I'd change it.