PHP获取select表单的选定值

PHP get selected value of select form

本文关键字:表单 获取 select PHP      更新时间:2023-09-26

我正在使用Laravel,目前正在创建一个表单,用户可以先选择一个类别,然后选择相关的子类别。

一个类别有一个id和一个名称,一个子类别有一个id和一个名称,以及一个parent_id(所以这是父类别的id)。

现在我尝试以下操作:用户可以选择一个类别,在他这样做之后,第二个select出现,用户可以从属于父类别的子类别中选择子类别(并且只有那些!)。

因此,视图从控制器获取所有类别和子类别。

然后,对于类别,我这样做:

<div class="form-group{{ $errors->has('category') ? ' has-error' : '' }}">
                                <label for="category" class="col-md-4 control-label">Kategorie</label>
                                <div class="col-md-6">
                                    <select>
                                        @foreach($categories as $category)
                                            <option value="<?php echo $category['id'];?>">{{$category->name}}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>

对于子类别,我有相同的,只是子类别:

<div class="form-group{{ $errors->has('subCategory') ? ' has-error' : '' }}">
                                <label for="subCategory" class="col-md-4 control-label">Unterkategorie</label>
                                <div class="col-md-6">
                                    <select>
                                        @foreach($subCategories as $subCategory)
                                            <option value="<?php echo $subCategory['id'];?>">{{$subCategory->name}}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>

现在的问题是:我需要做的是(在子类别foreach中)@if并检查category select的选定option的值,然后检查if($subcategory->parent_id == $chosenOptionID),以伪代码表示。我该怎么做呢?我不想发送表单之类的东西,在有人没有选择子类别之前....当然,我可以在选择类别时向控制器发送ajax请求,然后在控制器中检查选项的值并发回id。但这将导致非常大的流量,可能不是最好的解决方案,所以我想只这样做,如果我没有更好的方法来做....

PS:问题不是关于隐藏子类别时没有选择类别,这是基本的js,我知道如何做到这一点。我只是想知道,如果有可能读取category select的值,而窗体尚未发送。

EDIT:我现在尝试了AJAX的事情,但似乎有一个小错误…我改变了什么:

<div class="form-group{{ $errors->has('subCategory') ? ' has-error' : '' }}">
                                <label for="subCategory" class="col-md-4 control-label">Unterkategorie</label>
                                <div class="col-md-6">
                                    <select class="form-control" id="subCategorySelect">
                                    </select>
                                </div>
                            </div>

select现在是空的,并且有一个ID。然后在同一个文件中,我有以下JS:

<script>
    $().ready(function(){
        $('#categorySelect').change(function(){
            var selectedOption = $('#categorySelect').find(":selected").val();
            $.ajax({
                url: '/getSubCategories',
                data: {'id': selectedOption},
                type: 'GET',
                success: function (data) {
                    $('#subCategorySelect').html(data);
                }
            });
        });
    });
</script>

/getSubcategories路由指向控制器中的以下功能:

public function returnSubCategories(Request $request){
        $subCategories = Subcategory::where('parent_id', '=', $request->id);
        foreach($subCategories as $subCategory){
            echo "<option value='$subCategory->id'>$subCategory->name</option>";
        }
    }

但是它不工作…在选择一个选项时肯定会发送ajax请求,并发送正确的id。但不知何故,什么也没有输出……知道为什么吗?

我终于让它与AJAX一起工作了。这是我的初始subCategorySelect

<div class="form-group{{ $errors->has('subCategory') ? ' has-error' : '' }}">
                                <label for="subCategory" class="col-md-4 control-label">Unterkategorie</label>
                                <div class="col-md-6">
                                    <select class="form-control" id="subCategorySelect">
                                    </select>
                                </div>
                            </div>

select现在是空的,并且有一个ID。然后在同一个文件中,我有以下JS:

<script>
    $().ready(function(){
        $('#categorySelect').change(function(){
            var selectedOption = $('#categorySelect').find(":selected").val();
            $.ajax({
                url: '/getSubCategories',
                data: {'id': selectedOption},
                type: 'GET',
                success: function (data) {
                    $('#subCategorySelect').html(data);
                }
            });
        });
    });
</script>

/getSubcategories路由指向控制器中的以下功能:

public function returnSubCategories(Request $request){
        $subCategories = Subcategory::where('parent_id', '=', $request->id)->get();
        foreach($subCategories as $subCategory){
            echo "<option value='$subCategory->id'>$subCategory->name</option>";
        }
    }

效果很好。

希望这将帮助您了解它是如何与php工作的一个选择选项:

<div class="form-group">
    <label class="control-label" for="country">Country:<span>*</span></label>
    <select name="country" type="text" class="form-control" id="country">
        <option value="">--Country--</option>
        <?php
        include "../db/db.php"; //db-connection cause i want to load a country list
        $sql = "SELECT id, country_name FROM apps_countries ORDER BY country_name ASC";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) { //check if an entry is there
            while($row = $result->fetch_assoc()) { //get the values from the db
                //now this is the part you have to implement in your script
                if(isset($_POST["country"]) && $row["id"] == $_POST["country"]) { //check if country isset so if the user selected something
                    $optionSelected = "selected='selected'";
                } else{
                    $optionSelected = "";
                }
                //your foreache loop goes here / add the value that is selected here
                /*@foreach($categories as $category)
                        <option value="<?php echo $category['id']; ?>">{{$category->name}}</option> // get the associative array with "" and change it to $category["id"]
                @endforeach*/
                /**for my attempt it was this
                                {the id like as your category[id]}   {set the selected here inside the option tag}
                                                    ↓                  ↓                     */
                $countrySet = "<option value='" .$row["id"]. "' ".$optionSelected.">".$row["country_name"]."</option>";
                echo $countrySet;
            }
        }
        $conn->close();
        ?>
    </select>
</div>