简体   繁体   中英

How do i actually populate a multiple select box with php returned query, adding into multi dimensional array of jquery?

Sorry for my bad English as I'm not native English speaker.

The question is this, I have plan to do a three multiple select box in a single page, how to retrieve the query data before hand when the query in php is executed, individual query loop result will be add into a multidimensional array. 2nd, when the user click on any one of the option on the 1st multiple select box, it will structure the 2nd select box accordingly to the by calling out reference from array, how do i work on this? Lastly, I would like to do this without using ajax.

Here's part of my code, Javascript/jquery + php

$(document).ready(function(){

    var selectValues = { "1" : "General Health",
                         "2": "Head and Neck", 
                         "3": "Ear, nose and throat" ,
                         "4": "Stomach, bowel and bladder",
                         "5": "Bones and muscles",
                         "6": "Mental Health or confusion",
                         "7": "Pregnancy Problem",
                         "8": "Accident, wound or injury"
                         };

    var $cateSymptom = $('#cateSymptom');
    var $dropdownSymptom = $("#dropdownSymptom");

    $.each(selectValues, function(key, value) {   
     $('#cateSymptom')
         .append($("<option></option>")
         .attr("value",key)
         .text(value)); 
});

<?php

    $query = "select a.*, asy.*, s.* from ailment as a join symptom_ailment as asy on a.ailment_id = asy.ailment_id join symptom as s on asy.symptom_id = s.symptom_id";


    $result = mysqli_query($conn,$query) or die(mysqli_error($conn));


    while($row = mysqli_fetch_assoc($result))
    {
$sid = $row["symptom_id"];
$sname = $row["symptom_name"];
$stype = $row["stype_id"];
$aname = $row["ailment_name"];
$aid = $row["ailment_id"];

    echo "<script>alert('$sid $sname $stype $aname $aid'); </script>";
?>

    var selectValues2 = { "<?php echo $stype; ?>" : 
                                            {   
                                                "<?php echo $sname ?>" : 
                                                        [ 
                                                        "<?php echo $aid ?>",
                                                        "<?php echo $aname; ?>" 
                                                        ]
                                            }
                        };


<?php }
 ?>

    $cateSymptom.change(function() {
    alert('1');
        $dropdownSymptom.empty().append(function() {

            alert('2');
            var output = '';
            console.debug(selectValues2);
            $.each(selectValues2[$cateSymptom.val()], function(key, value) {
            alert('3');
                output += '<option>' + key + '</option>';
            });
            return output;

        });

    }).change();

    }); 

HTML:

<div id="scCategory">
<h3>Choose Symptoms Category</h3>
<form name="frmSC2" method="POST" id="frmSC2">

<select multiple name="symp[]" id="cateSymptom"  style="width:230px;height:280px;">
</select>
</div>

<div id="scDepth">
<h3>List of Symptoms</h3>
<select multiple name="symptom[]" id="dropdownSymptom"  style="width:230px;height:280px;">
</select>
</div>

<div id="scCondition">
<h3>Possible Condition</h3>
<select multiple name="condition[]" id="dropdownCondition"  style="width:230px;height:240px;">
</select>
</div>

Following is a fully integrated solution for all 3 levels

Data structure uses objects with ID as keys, and a children property if applicable

var data = {
   "1": {
      "val": "1",
      "text": "General Health",
      "children": {
         "1.0": {
            "text": "Item - 1.0",
            "val": "1.0",
            "children": {
               "1.0.0": {
                  "text": "Item - 1.0.0",
                  "val": "1.0.0"
               }
            }
         }
}

In the JS the active data for each select is storedd on the element using jQuery data() for easy access to populate the next select within change handler

/* change handler to manage emptying and populating chained selects */
var $selects = $('select').change(function () {
    var idx = $selects.index(this),
        $currSelect = $(this),
        val = $currSelect.val(),
        $nextSelect = $selects.eq(idx + 1);
    if (idx < 2) {
        /* empty select(s) after this one */
        $selects.filter(':gt(' + idx + ')').empty();

        /* if value update next select */
        if (val) {
            var nextSelectData = $currSelect.data('selectData')[val].children;
            populateSelect($nextSelect, nextSelectData);
        }
    }
});
/* load first select */
populateSelect($selects.first(), data);

function populateSelect($select, selectData) {
    $select.append('<option value=""> -- Select -- </option>')
    $.each(selectData, function (key, item) {
        $select.append($("<option></option>")
            .attr("value", key)
            .text(item.text));
    });
    /* store the data on this element for easy access in change handler */
    $select.data('selectData', selectData);

}

DEMO

Since you don't want to use ajax.. The VERY DIRTY way to do this would be to output the PHP array on the page as something like an unordered list (and display:none; or jquery.hide) on those said lists. Point at them with Jquery like so:

var list1 = [];
$('classListOne.li').each(function(i, elem) {
    list1.push($(elem).text());
});

Then at that point since you need the next drop down's to reflect what a user implemented on the first drop down. Your going to need to create a pretty hariy IF/else and or CASE statement in Jquery. Once you find the array you need create a another drop-down and append it to where you need it to go like so:

var data = {
    'foo': 'bar',
    'foo2': 'baz'
}

var s = $('<select />');

for(var val in data) {
    $('<option />', {value: val, text: data[val]}).appendTo(s);
}

s.appendTo('body');

This again is a horrible why to do this, but I understand sometimes you can't always use the best technologies. Let me know if that helps at all.

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