Akio Akio - 1 month ago 11
CSS Question

Passing select value to another select tag

I am using Materialize CSS as my CSS framework and I also wasted 1 hour searching for the answers in google/stackoverflow etc.. but I can't seem to find the answer to solve this problem. So, what I am doing is I'm trying to pass the value of Select 1 to Select 2. Here is my code below

Select 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>


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);
})


Other JS that I have tried is:

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


Rendered Select 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>


Rendered 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>


Thanks in advance for those who will answer and help me!

Answer

Use event delegation to listen for changes on the Accounts select instead:

$("#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);
});

See this jsFiddle for a working example.

Materialize CSS does a lot of modifications to the DOM when it renders its components, making straightforward JavaScript operations on UI elements from your part break at times.