将选择值传递给另一个选择标记

时间:2016-10-16 14:06:04

标签: javascript jquery css materialize

我使用Materialise CSS作为我的CSS框架,我也浪费了1个小时在google / stackoverflow等中搜索答案。但我似乎找不到解决这个问题的答案。所以,我正在做的是我试图将Select 1的值传递给Select 2.这是我的代码

选择1:

<select id="Accounts">
  <option value="">Choose Account to edit</option>
     <?php
        $query  = "SELECT * FROM personnel_list WHERE status = ?";
        $result = $this->db->query($query, array("Active"))->result_array();
        foreach ($result as $row) {
           extract($row);
           echo "<option value=\"$id-$name-$position-$status\">$name</option>";
        }
   ?>
</select>

选择2:

<select id="editPosition">
    <option value="">Choose Position</option>
        <?php
            $Position = array("Manager", "Supervisor", "Assistant Manager", "Assistant Supervisor")
            for ($x=0; $x < count($Position); $x++) { 
                echo "<option value=\"$Position[$x]\">$Position[$x]</option>";
            }
        ?>
</select>
<label for="editPosition">Position:</label>

JS:

$("#Accounts").change(function(){
var accval  = $(this).val().split("-");
var id      = accval[0];
var name    = accval[1];
var post    = accval[2];
var status  = accval[3];

$("#editPosition").val(post);
})

我尝试的其他JS是:

$("#editPosition option[value='"+post+"']").prop("selected", true);

渲染选择1:

<select id="Accounts">
<option value="">Choose Account to edit</option>
<option value="1-John-Manager-Active">John</option><option value="2-Mark-Assistant Manager-Active">Mark</option>
</select>

渲染选择2:

<select id="editPosition">
<option value="">Choose Position</option>
<option value="Manager">Manager</option>
<option value="Supervisor">Supervisor</option>
<option value="Assistant Manager">Assistant Manager</option>
<option value="Assistant Supervisor">Assistant Supervisor</option>
</select>

提前感谢那些愿意回答并帮助我的人!

1 个答案:

答案 0 :(得分:2)

使用事件委派来监听Accounts选择的更改:

$("#Accounts").on("change", function(){
    var accval  = $(this).val().split("-");
    var id      = accval[0];
    var name    = accval[1];
    var post    = accval[2];
    var status  = accval[3];

    $("#editPosition").val(post);
});

有关工作示例,请参阅this jsFiddle

Materialise CSS在呈现其组件时对DOM进行了大量修改,从而在您的部件中对UI元素进行简单的JavaScript操作。