Home  >  Q&A  >  body text

javascript - How to select different option values ​​based on the values ​​passed from the background in html select

Code:

 <tr>
    <th>空间性质</th>
     <td>
         <input type="hidden" id = "class" value="{$post.post_class}"/>

         <select class="form-control" name="post[post_class]" id="class2" value="{$post.post_class}">
         <option value="0" id="op1">出售</option>
         <option value="1" id="op2">出租</option>
         </select>
         </td>
 </tr>

Display different option values ​​​​according to the value of value={$post.post_class}, value only has two values ​​​​0 and 1. TKS

淡淡烟草味淡淡烟草味2672 days ago1180

reply all(5)I'll reply

  • 黄舟

    黄舟2017-06-28 09:27:35

    The default selection is right, just use jquery's attr. Assuming that the default selection value is 1, the code is as follows:

    $("#class option[value='1']").attr('selected',true);

    reply
    0
  • 巴扎黑

    巴扎黑2017-06-28 09:27:35

    Isn’t it enough to just set the value in the select tag to 0 or 1?

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-06-28 09:27:35

    $("#class option[value='1']").attr('selected',true);
    或
    $("#class").val(1);

    reply
    0
  • 世界只因有你

    世界只因有你2017-06-28 09:27:35

    http://jsrun.net/d9YKp

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-06-28 09:27:35

    Due to: document.querySelector('#class').valueThe value in select cannot be obtained (i.e. <select class="form-control" name="post[post_class]" id="class2" value="{$post.post_class}">).

    So add a hidden input <input type="hidden" id = "class" value="{$post.post_class}"/> to get the value sent from the background, and then judge.

    <script type="text/javascript">
        var sv = document.getElementById('class').value;
        if(sv == 0){
            $("#class2 option[value='0']").attr('selected',true);
        }else {
            $("#class2 option[value='1']").attr('selected',true);
        }
    </script>

    reply
    0
  • Cancelreply