繁体   English   中英

如何在需要时仅提交隐藏/显示字段数据之一 - Laravel

[英]How to submit only one of hide/show fields data when required - Laravel

一个表单包含多个字段。 一个字段是“是/否”下拉列表。 选择是时,会出现另一个下拉列表。 当未选择时,会出现文本输入字段。 根据是/否下拉列表,应将字段数据之一提交到数据库。

但是,这两个字段的数据都会发送到数据库。 但是数据库想要一个字符串,现在它得到了一个数组。 可以提交数据。 应该采取什么措施来防止这种情况发生,所以只有来自显示字段的数据通过控制器,而不是来自当时隐藏字段的数据?

注意:需要填写 1 个字段(下拉列表的输入)。

查询
 window.onload = function() { document.getElementById('ifYes').style.display = 'none'; document.getElementById('ifNo').style.display = 'none'; } function hideShow() { var D = document.getElementById("yesno") var Y = document.getElementById('isYes') var N = document.getElementById('isNo') if (D.selected) { if (D.value == "yes"){ Y.style.display = 'block'; N.style.display = 'none'; Y.required = true; } else{ N.style.display = 'block'; Y.style.display = 'none'; N.required = true; } } }
HTML
 <div class="row"> <div class="col-6"> <select name="agree" class="form-control" onchange="hideShow();" id="yesno" required> <option></option> <option id="yes">Yes</option> <option id="no">No</option> </select> </div> <div class="col-6"> <select name="type" class="form-control" id="ifYes"> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> </select> <input type="text" id="ifNo" class="form-control input-text" name="type"> </div> </div> <div class="row"> <button type="submit" class="btn btn-primary btn-block" style="margin: 10px;">New</button> </div>

在我的控制器中,我已经对研究所说需要进行了验证。 现在,我删除它。 通过调整 javascript 代码,错误消失了。

$this->validate($request, [
            'institute'             => 'min:2', 
            ...
]); 

$project = new Project();
...
$project->type = request('type');
...
$project->save();

Javascript 添加禁用字段

    function hideShow() {

        var x = document.getElementById('YesNo');
        var r = x.options[x.selectedIndex].value;
        var y = document.getElementById("ifyes");
        var n = document.getElementById("ifno");
        if ( r == "Yes"){
            y.style.display = "block";
            n.style.display = "none";
            y.disabled = false;
            n.disabled = true;
        y.required = true;
        n.required = false;
        }
        else if ( r == "No") {
            y.disabled = true;
            n.disabled = false;
            y.style.display = "none";
            n.style.display = "block";
        y.required = false;
        n.required = true;
        } else{
            y.disabled = true;
            n.disabled = true;
            y.style.display = "none";
            n.style.display = "none";
        y.required = false;
        n.required = true;
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM