如何在不提交的情况下将选定的下拉值存储到php变量?

时间:2018-06-18 13:51:16

标签: javascript php html

我有下拉菜单。当我选择任何值并单击确认时,在它下面应打印所选值,并且所选值也应显示在下拉列表中。我怎样才能做到这一点。

<!DOCTYPE html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <!--Links related to dropdown-->
    <link href="http://localhost/performance/Test/css/fselect.css" rel="stylesheet">
    <script src="http://localhost/performance/Test/js/fSelect.js"></script>

     <script>
    (function($) {
        $(function() { 
            $('#project_name').fSelect();
        });
    })(jQuery);
    </script>
</head>

<body>
    <?php
        $projects = array('Trial','Test','Birds','Animals');
    ?>

    <div class="container">
        <div><center><b>This test will be created in the selected project:</b></center></div><br>
        <div class="create_test">
            <form action="#" method="post">
                <div style="margin-left:2cm;">
                    <select  name="project_name" id="project_name" >
                        <?php
                            for($i=0; $i<count($projects); $i++) {
                                echo "<option value='".$projects[$i]."'>".$projects[$i]."</option>";    
                            }
                        ?>
                    </select>
                    <input type="submit" style="margin-left:3.5cm; width:140px;" name="submit"  id="comfirm" class="btn btn-success" value="Confirm" />
                </div>
            </form>
        </div>
    </div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

<?php 
/** Store selected in a varaible in php */
$selected = 'trial';// Suppose get the value from db here
                            for($i=0; $i<count($projects); $i++) {
                                echo "<option value='".$projects[$i]."' selected='".$project[$i] == $selected."'>".$projects[$i]."</option>";    
                            }
                        ?>

因此添加所选的=&#39; true&#39;将用作选择标记的值