普通网友 2018-04-19 18:12
浏览 14

循环内的功能

I've been staring at code all day, and I just can't seem to find what im looking for, I know how to do this with PHP but I'm new to dynamic stuff.

This code is inside a loop that is generated by a database. The dropdown items are fixed, but each individual is inside a database. I want to be able to choose the next drop down box selections based on the first one. This code works but not for each individual in the loop. Each item in the loop just updates the top one.

<div class="grid-container-fluid" style="margin-bottom: 25px;">
    <div class="grid-container" style="font-family: 'Roboto Condensed', sans-serif;">
        <div class="grid-x align-center">
        <div class="large-10 cell">
            <div class="grid-x">

                <?php
                    if ($result->num_rows > 0) {

                        echo '<div class="large-12 cell">';
                            echo '<p style="font-family: Roboto Condensed, sans-serif; letter-spacing: 2px; font-weight: bold; line-height:1; font-size: 30px;">ADMIN PANEL:</p>';
                            echo '<p style="font-family: Roboto Condensed, sans-serif; font-size: 20px;">Income: $'.$total.'/mo<br>Program Value: $'.$value.'/person</p>';
                        echo '</div>';


                        echo '<div class="large-12 hide-for-small-only cell" style="border-bottom: 3px black solid; padding-bottom: 5px;">';
                            echo '<div class="grid-x">';
                                echo '<div class="medium-auto small-6 cell">';
                                    echo '<p align="left" style="margin: 0;">NAME</p>';
                                echo '</div>';

                                echo '<div class="medium-auto small-6 cell">';
                                    echo '<p align="left" style="margin: 0;">EMAIL</p>';
                                echo '</div>';

                                echo '<div class="medium-auto small-6 cell">';
                                    echo '<p align="left" style="margin: 0;">PROGRAM</p>';
                                echo '</div>';

                                echo '<div class="medium-auto small-6 cell">';
                                    echo '<p align="left" style="margin: 0;">PLAN</p>';
                                echo '</div>';

                                echo '<div class="medium-2 small-6 cell">';
                                    echo '<p align="left" style="margin: 0;">STATUS</p>';
                                echo '</div>';

                                echo '<div class="medium-1 small-12 cell" style="padding-left: 15px;">';
                                        echo '<p style="margin:0; text-align: center">';
                                            echo '<i class="fi-wrench"></i>';
                                        echo '</p>';
                                echo '</div>';
                            echo '</div>';
                        echo '</div>';

                        // output data of each row
                        while($row = $result->fetch_assoc()) {

                            echo '<div class="large-12 cell" style="border-bottom: 1px black solid; padding: 5px;">';

                                    echo '<div class="grid-x align-middle">';
                                        echo '<div class="medium-auto small-12 cell" style="padding:2px;">';
                                            echo '<input style="background-color: white; border: 0; margin: 0;" value="'.$row["name"].'" name="name">';
                                        echo '</div>';

                                        echo '<div class="medium-auto small-12 cell" style="padding:2px;">';
                                            echo '<input style="background-color: white; border: 0; margin: 0;" value="'.$row["email"].'" name="email">';
                                        echo '</div>';


                                        echo '<div class="medium-auto small-12 cell" style="padding:2px;">';
                                        echo '<select style="margin: 0; height: auto; border: 0;" name="program" id="program" onChange="changecat(this.value, '.$value.');">';
                                            echo '<option value="" disabled selected>'.$row["program"].'</option>';
                                            echo '<option value="Hockey">Hockey</option>';
                                            echo '<option value="Fundamentals">Fundamentals</option>';
                                        echo '</select>';
                                        echo '</div>';

                                        echo '<div class="medium-auto small-12 cell" style="padding:2px;">';
                                        echo '<select style="margin: 0; height: auto; border: 0;" name="plan" id="plan">';
                                            echo '<option value="" disabled selected>'.$row["plan"].'</option>';
                                        echo '</select>';
                                        echo '</div>';
                                        ?>

                                        <script>

                                            var programsByplan = {
                                                Hockey: ["Off Season", "Pre Season", "In Season"],
                                                Fundamentals: ["Phase 1"],
                                            }

                                            function changecat(value) {
                                                if (value.length == 0) document.getElementById("plan").innerHTML = "<option></option>";
                                                else {
                                                    var catOptions = "";
                                                    for (planId in programsByplan[value]) {
                                                        catOptions += "<option>" + programsByplan[value][planId] + "</option>";
                                                    }
                                                    document.getElementById("plan").innerHTML = catOptions;
                                                }
                                            }

                                        </script>





                                        <?php
                                        echo '<div class="medium-2 small-12 cell">';
                                            echo '<div class="grid-x align-middle">';

                                                echo '<div class="small-6 cell">';
                                                    echo '<select style="margin: 0; height: auto; border: 0;" name="week">';
                                                        echo '<option value="'.$row["week"].'">' . 'Week ' . $row["week"] . '</option>';
                                                        echo '<option value="1">Week 1</option>';
                                                        echo '<option value="2">Week 2</option>';
                                                        echo '<option value="3">Week 3</option>';
                                                        echo '<option value="4">Week 4</option>';
                                                        echo '<option value="5">Week 5</option>';
                                                        echo '<option value="6">Week 6</option>';
                                                        echo '<option value="7">Week 7</option>';
                                                        echo '<option value="8">Week 8</option>';
                                                        echo '<option value="9">Week 9</option>';
                                                        echo '<option value="10">Week 10</option>';
                                                        echo '<option value="11">Week 11</option>';
                                                        echo '<option value="12">Week 12</option>';
                                                        echo '<option value="13">Week 13</option>';
                                                        echo '<option value="14">Week 14</option>';
                                                        echo '<option value="15">Week 15</option>';
                                                    echo '</select>';
                                                echo '</div>';

                                                echo '<div class="small-6 cell">';
                                                    echo '<select style="margin: 0; height: auto; border: 0;" name="day">';
                                                        echo '<option value="'.$row["day"].'">' . 'Day ' . $row["day"] . '</option>';
                                                        echo '<option value="1">Day 1</option>';
                                                        echo '<option value="2">Day 2</option>';
                                                        echo '<option value="3">Day 3</option>';
                                                        echo '<option value="4">Day 4</option>';
                                                    echo '</select>';
                                                echo '</div>';
                                            echo '</div>';
                                        echo '</div>';

                                        echo '<div class="medium-1 small-12 cell" style="padding-left: 15px;">';
                                            echo '<p style="margin:0; text-align: center">';
                                                echo '<input style="font-size: 12px;" class="expanded button nav" type="submit" value="Update" name="submit" id="submit"/>';
                                            echo '</p>';
                                        echo '</div>';

                                    echo '</div>';
                            echo '</div>';
                        }
                    }
                ?>
            </div>
        </div>
        </div>
    </div>
</div>

I know it needs a unique id, I just can't figure out where.

  • 写回答

1条回答 默认 最新

  • 笑故挽风 2018-04-19 19:19
    关注

    Something like this:

    echo '<div class="medium-auto small-12 cell" style="padding:2px;">';
    echo '<select style="margin: 0; height: auto; border: 0;" name="program" id="program-'.$row['id'].'" >';
        echo '<option value="" disabled selected>'.$row["program"].'</option>';
        echo '<option value="Hockey">Hockey</option>';
        echo '<option value="Fundamentals">Fundamentals</option>';
    echo '</select>';
    echo '</div>';
    
    echo '<div class="medium-auto small-12 cell" style="padding:2px;">';
    echo '<select style="margin: 0; height: auto; border: 0;" name="plan" id="plan-'.$row['id'].'">';
        echo '<option value="" disabled selected>'.$row["plan"].'</option>';
    echo '</select>';
    echo '</div>';
    ?>
    
    <script>
        var programsByplan = {
            Hockey: ["Off Season", "Pre Season", "In Season"],
            Fundamentals: ["Phase 1"],
        }
    
        $('select[name="program"]').change(function(){
            var program = $(this).val();
            var plan_id = $(this).prop('id').replace('program', 'plan');
            if(programsByplan[program]){
                var options = [];
                $.each(programsByplan[program], function(i,v){
                    options.push('<option value="'+v+'">'+v+'</option>');
                });
                $('#'+plan_id).html(options.join("
    "));
            }else{
                //or, do somkind of error recovery here.
               $('#'+plan_id).html('<option value="">No Plans</option>');
            }
        });
    </script>
    

    I would get rid of the onChange, I'm also making heavy use of jQuery, but the question is tagged with it.

    So on the change of any select with the name program (which we haven't changed, so they all have the same name) we trigger the event callback. You could also do this part with a class, of course.

    In the callback we get the value selected in the current select, then we check that it exists in programsByplan (which it always should) but doesn't hurt to check.

    Then we convert the program id program-'.$row['id'].' to plan-'.$row['id'].'. Now we know which plan select to change. I prefer using an array to add the options, but you could do the += thing. And then it's a simple matter to replace them, now that we know the plan elements id, with .html().

    I haven't tested this but it should be pretty close. The big thing is setting yourself up to succeed by having the id easy to correlate, or in other words easy to find the right plan element for the changed program element.

    I am also assuming you have a $row['id'] that is at least unique to the loop that generates these.

    Update

    But how do I get the options to show up on page load when the program/plan is proper from the database

    I would further change it like this:

    //outside of the loop define your data
    $programsByplan = [
            'Hockey' => ["Off Season", "Pre Season", "In Season"],
            'Fundamentals' => ["Phase 1"],
    ];
    
    //inside the loop
    echo '<div class="medium-auto small-12 cell" style="padding:2px;">';
    echo '<select style="margin: 0; height: auto; border: 0;" name="program" id="program-'.$row['id'].'" >'; 
        foreach($programsByplan as $program => $plans){
            //$selected = $row["program"] == $program ? 'disabled selected' : '';
            $selected = $row["program"] == $program ? 'selected="selected"' : '';
            echo '<option value="'.$program.'" '.$selected.'>'.$program.'</option>';
        }
    echo '</select>';
    echo '</div>';
    
    echo '<div class="medium-auto small-12 cell" style="padding:2px;">';
    echo '<select style="margin: 0; height: auto; border: 0;" name="plan" id="plan-'.$row['id'].'">';
        foreach($programsByplan[$row["program"]] as $plan){
            //$selected = $row["plan"] == $plan ? 'disabled selected' : '';
            $selected = $row["plan"] == $plan ? 'selected="selected"' : '';
            echo '<option value="'.$plan.'" '.$selected.'>'.$plan.'</option>';
        }
    echo '</select>';
    echo '</div>';
    ?>
    
    <script>
        var programsByplan = <?php echo json_encode($programsByplan); ?>;
    
        //... other code
    

    Here we are adding $programsByplan in PHP, then with json_encode we can add the same array to Javascript, which is awesomeness. Hopeful this works

    var programsByplan = <?php echo json_encode($programsByplan); ?>;
    

    Sometimes it can take a bit of fiddling to, but it has huge benefits in maintainability for the code. Because you are using only one authoritative source for the data for that. As opposed to it being spread everywhere. A side benefit of this is, if you go and make the programs and plans as two tables with a Many to One relationship you could put those in the DB and easily update the code by building that array. See if the data is just spread out hard coded then it's difficult to make changes like that later.

    It also lets us fix a few of the other issues you had with building the selects originally, and just simplifies the code. One big issue was removing the value on the selected items, and having duplicate items.

      echo '<option value="" disabled selected>'.$row["program"].'</option>';
    

    You are actually removing the value here, which is probably not what you want. I am also not sure about the disabled bit, so I just left that in. Maybe that was just there to fix the selection issues from initializing it? Anyway I put that part in a comment. I've always done selected like this:

    $selected = $row["program"] == $program ? 'selected="selected"' : '';
    

    It's probably the "old-school" way of doing it but it always worked for me.

    Anyway, and obviously if we try to get the value of the selected option and its value has been removed, it probably wont work out to good. Not to mention there is no way to "know" what that is to remove the option with the same value when it's just hard coded in like it was and so you'll wind up with a duplicate option for it.

    This should fix most of that, but this is all done in my head, so hopefully it all works out like I am thinking it should. The theory is sound anyway.

    You can test it in this sandbox:

    http://sandbox.onlinephpfunctions.com/code/077c8a988697122549713ede9c305bf4f7620ed9

    using (As canned data for a row.)

    $row = [
        'id' => 1,
        'program' => 'Hockey',
        'plan' => 'Off Season'
    ];
    

    Which outputs:

    <div class="medium-auto small-12 cell" style="padding:2px;">
        <select style="margin: 0; height: auto; border: 0;" name="program" id="program-1" >
            <option value="Hockey" selected="selected">Hockey</option>
            <option value="Fundamentals" >Fundamentals</option>
        </select>
    </div>
    
    <div class="medium-auto small-12 cell" style="padding:2px;">
        <select style="margin: 0; height: auto; border: 0;" name="plan" id="plan-1">
            <option value="Off Season" selected="selected">Off Season</option>
            <option value="Pre Season" >Pre Season</option>
            <option value="In Season" >In Season</option>
        </select>
    </div>
    

    As you can see we have program-1 and plan-1 our ID's, then both selects have the proper element with selected="selected"

    Update2

    To handle cases where no data was previously selected for the program.

    For the first loop above I would add this

     //echo <select ...
     echo '<option value="" > - Please select a program - </option>';
     //foreach( ...
    

    Do it before the loop and after the opening for the <select. Then for the second loop I would disable the second select, until they make a choice in the first.

    $disabled = empty($row["program"]) ? 'disabled="disabled"': '';
    echo '<select style="margin: 0; height: auto; border: 0;" name="plan" id="plan-'.$row['id'].'" '.$disabled.'>';
    

    And then in the Javascript

    $('select[name="program"]').change(function(){
        var program = $(this).val();
        if(program == '' ) return; //exit on empty selection
        var plan_id = $(this).prop('id').replace('program', 'plan');
        //enable the select if disabled.
        $('#'+plan_id).attr('disabled',false);
    

    Then you may just want to check before saving it that they selected a program etc. etc..

    Update3

    For any Javascript issues always use the debug window in the browser (f12) then click on console. Then in your code you can just do like

    console.log(var);
    

    And it will print that value in the console. It's simular to PHP's var_export, print_r or var_dump etc...

    So I would start with this

     <script>
        var programsByplan = <?php echo json_encode($programsByplan); ?>;
        console.log(programsByplan);
    
    
        $('select[name="program"]').change(function(){
            var program = $(this).val();
    
            console.log(program);
    
            var plan_id = $(this).prop('id').replace('program', 'plan');
    
            console.log(programsByplan[program]);
    
            if(programsByplan[program]){
                var options = [];
                $.each(programsByplan[program], function(i,v){
                    options.push('<option value="'+v+'">'+v+'</option>');
                });
                $('#'+plan_id).html(options.join("
    "));
            }else{
                //or, do somkind of error recovery here.
               $('#'+plan_id).html('<option value="">No Plans</option>');
            }
        });
    </script>
    

    And so on and see what the values are. That's probably the best way.

    Cheers.

    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题