I have the following select
on my form
<select id="select-1">
<option value="11">Option 11</option>
<option value="12">Option 12</option>
<option value="13">Option 13</option>
</select>
And a hidden input
<input id="hidden-input-1" value="13">
When my page loads, hidden-input-1
could have a value of either 11, 12, or 13. I'd like to default my select to whatever the value of this input might be. So far I've tried to set this using .val():
$( document ).ready(function() {
/*...
do AJAX stuff to set input value
...*/
$("#select-1").val($("#hidden-input-1").val());
});
Which just returns a blank selection. Any ideas on how to nail this?
You are trying to access the elements when they are not loaded into DOM, so you are not getting any value, Below the correct way to do.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select-1">
<option value="11">Option 11</option>
<option value="12">Option 12</option>
<option value="13">Option 13</option>
</select>
<input id="hidden-input-1" value="13">
<script>
$(document).ready(function() {
$("#select-1").val($("#hidden-input-1").val());
});
</script>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments