简体   繁体   中英

Default Select Option Based on Input Value

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?

$("#hidden-input-1").val('12');
var value = $("#hidden-input-1").val();
alert(value);
$("#select-1").val(value);

FIDDLE

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> 

/*... do AJAX stuff to set input value ...*/

$.ajax() is asynchronous ; $("#select-1").val($("#hidden-input-1").val()); appear synchronous , could be called before $.ajax() completes setting hidden input value ? if outside of , following $.ajax() success , error callbacks.

Try calling $("#select-1").val($("#hidden-input-1").val()); at complete handler of ajax call

$.ajax().then(function() {
  /*...
     do AJAX stuff to set input value
...*/
  // set `select` value when `input` value set
  $("#select-1").val($("#hidden-input-1").val());

}, function err(jqxhr) {
  console.log(jqxhr.status)
})

`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM