简体   繁体   中英

How to store a selected dropdown value to a php variable without submitting?

I have dropdown. When I select any value and click on confirm, Below it should print the selected value and also the selected value should be shown in the dropdown. How can I achieve this.

<!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>
<?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>";    
                            }
                        ?>

So adding the selected='true' will be used as value for the select tag

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