首页 > 解决方案 > 将隐藏值链接/关联到表单上的特定单选按钮 (PHP/MySQL/HTML)

问题描述

我正在使用链接到 MySQL 数据库的 PHP 创建一个表单。

我有多个问题,每个问题都需要回答是或否。

我已经设置了表单,以便将 Yes 和 No 响应提交到数据库。但是,如果用户选择否,我需要一个隐藏值(为什么会选择否的预定义详细信息)提交到数据库上的不同表。目前,在提交时,无论用户选择yes还是no,都会提交隐藏值。

我的代码如下:

<label for="question1" class="input_labels">1. Confidentiality protocols were adhered to</label>
                                <input class="form-check-input-line" type="radio" name="question1" id="question1" value="YES">  YES
                                <input class="form-check-input-line" type="radio" name="question1" id="question1" value="NO">  NO <br>
                                <input type="hidden" id="error1" name="error1" value="Confidentiality protocols were not adhered to">

query1 是提交实际的 Yes / No 响应,而 query2 是提交隐藏值(我尚未将所有详细信息添加到 query2,因为我正在尝试测试它是否首先工作):

$query1 = "INSERT INTO questions 
        
                    (questionsID, question1, question2, question3, question4, question5, question6, question7, question8, question9, question10, question11, question12, question13, question14, question15, question16, question17, question18, question19, question20, question21, question22, question23, question24) 

                 VALUES 
                 
                    (NULL, '$question1', '$question2', '$question3', '$question4', '$question5', '$question6', '$question7', '$question8', '$question9', '$question10', '$question11', '$question12', '$question13', '$question14', '$question15', '$question16', '$question17', '$question18', '$question19', '$question20', '$question21', '$question22', '$question23', '$question24')";

        $result1 = mysqli_query( $conn, $query1);   
        
        } else {
    
        $submitError = "The form was not submitted, please try again <br>";

}

$query2 = "INSERT INTO fixable_errors 
        
                    (fixableID, error1) 

                 VALUES 
                 
                    (NULL, '$error1')";

        $result2 = mysqli_query( $conn, $query2);

标签: phphtmlmysqlforms

解决方案


好吧,我希望您发布您的 JavaScript 代码,但是您需要做的是仅在用户选择“是”单选按钮时禁用隐藏的输入字段,这样,隐藏的输入不会与其他输入一起提交.

JS

var radioBtns = document.getElementsByName("question1");
var hiddenInput = document.getElementById("error1");

radioBtns.forEach(function(btn) {
    btn.addEventListener("click", function() {
        var radioValue = this.value;
        if (radioValue == "Yes") { // case-sensitive
            hiddenInput.setAttribute("disabled", "");
        } else {
            hiddenInput.removeAttribute("disabled");
        }
    });
});

上面的代码在用户单击 YES 时禁用隐藏字段,并在用户单击 NO 时启用它。

现在在您的 PHP 代码中,您可以使用该isset()函数检查隐藏字段的值是否也已提交。请参阅下面的代码

PHP

// check if input with name 'error1' was submitted
if(isset($_POST['error1']){
    $error1 = $_POST['error1'];
    $query2 = "INSERT INTO fixable_errors (fixableID, error1) VALUES (NULL, '$error1')";
    $result2 = mysqli_query( $conn, $query2);
}

推荐阅读