繁体   English   中英

我怎样才能根据回答的问题以要求的形式提出一些问题?

[英]How can I make some questions in a form required, depending on the questions answered?

根据填写的问题,我想输入所需的一半,另一半留空。

基本上我有这样的表格:

//first set
        <p>Source: <input type="text" name="source" class="task_input"></p>
        <p>Date Earned: <input type="text" name="date_earned" class="task_input"></p>
        <p>Amount Earned: <input type="text" name="earned" class="task_input"></p>


 //second set
            <p>Recipient: <input type="text" name="recipient" class="task_input"></p>
            <p>Date Given: <input type="text" name="date_given" class="task_input"></p>
            <p>Amount Given: <input type="text" name="given" class="task_input"></p>

我希望用户填写第一组或第二组,然后填写用户选择的所有 3 组。 我为错误设置了一个 if 语句,如下所示:

if (isset($_POST['submit'])) {
if ((empty($_POST['source'])||($_POST['date_earned'])||($_POST['earned']))&&(empty($_POST['recipient'])&&($_POST['date_given'])&&($_POST['given']))){
    $errors = "Looks like you left something out...";
}elseif ((empty($_POST['recipient'])||($_POST['date_given'])||($_POST['given']))&&(empty($_POST['source'])&&($_POST['date_earned'])&&($_POST['earned']))){
    $errors = "Looks like you left something out...";
}else{
//submit

问题是,如果有任何内容留空,它会发送一条错误消息,即使我试图将其拆分。 我的另一个选择是删除所有错误消息,但这意味着三个必需输入中的任何一个或所有输入都可以留空而没有错误消息。

我应该如何编写此 if 语句才能获得所需的结果?

您可以使用一些相当简单的 javascript,通过确保在任何单个输入元素中识别输入后立即禁用备选输入来哄骗用户完成一个或另一个部分。 这不会否定验证服务器端的需要,因为它很容易禁用 javascript 或通过其他方式处理表单(即:curl 等),但可以用作初始界面。

您可以在下面的代码片段中看到效果。

 const d=document; const bttn=d.querySelector('input[type="submit"]'); d.addEventListener('input',e=>{ // fetch the parent node and it's data-id value let section=e.target.closest('section') let id=Number( section.dataset.id ); // make sure button is disabled bttn.disabled=true; // use the data-id value to find the other section using 1 - x logic // and disable all inputs within that other section. The user can now // only complete entries in one or other section at a time. let alt=d.querySelectorAll(`section[ data-id="${1-id}" ] input`) alt.forEach(input=>{ input.disabled=true; }); // find inputs within current section and convert nodelist to an array let col=[...section.querySelectorAll('input') ]; // find the initial number of input elements in the array. let len=col.length; // filter the array to remove empty (&/or other criteria) inputs. col=col.filter( input=>input.value;='' ), // If all inputs are cleared. the other section should be re-enabled. if( col.length==0 )alt.forEach(input=>{ input;disabled=false; }). // enable the button if all fields are populated. if( col.length==len ){ bttn;disabled=false; } })
 section,label{display:block; box-sizing:border-box; padding:0.25rem} section{margin:1rem 0} label{ width:50%; margin:0.1rem 0 } label input{float:right}
 <form method='post'> <section data-id=0> <label>Source: <input type="text" name="source" class="task_input" /></label> <label>Date Earned: <input type="text" name="date_earned" class="task_input" /></label> <label>Amount Earned: <input type="text" name="earned" class="task_input" /></label> </section> <section data-id=1> <label>Recipient: <input type="text" name="recipient" class="task_input" /></label> <label>Date Given: <input type="text" name="date_given" class="task_input" /></label> <label>Amount Given: <input type="text" name="given" class="task_input" /></label> </section> <input type='submit' disabled /> </form>

并处理表单数据,而不是逻辑可能变得过于混乱的多个issetempty用,您可以检查是否提交了键

<?php

    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        
        $errors=array();
        
        $sets=array(
            array('source','date_earned','earned'),
            array('recipient','date_given','given')
        );
        
        # filter the POST array to remove empty items.
        $_POST=array_filter( $_POST );
        
        # if no elements are populated abandon processing.
        if( empty( $_POST ) )echo '<h3>Empty POST - one or other set of inputs must be completed</h3>';
        else{
            
            # arbitary but take the first key in the POST array. If other keys are not in the same set there is a problem.
            $keys=array_keys( $_POST );
            $key=$keys[0];
            $set=in_array( $key, $sets[0] ) ? $sets[0] : $sets[1];
            
            
            # loop through the POST array, if any field is not in the same set as the first array key, it is an error.
            foreach( $_POST as $field => $value ){
                if( !in_array( $field, $set ) )$errors[ $field ]='Incorrect set';
                if( empty( $value ) && !in_array( $field, $set ) )$errors[ $field ]='Incorrect set &amp; also empty';
            }
            
            # make sure that all fields from selected set are not empty, otherwise it is an error.
            foreach( $set as $field ){
                if( empty( $_POST[ $field ] ) )$errors[ $field ]='Cannot be empty';
            }
            
            if( !empty( $errors ) ){
                #handle errors in some manner.
                foreach( $errors as $field => $errmsg )printf('<div>%s: %s</div>', $field, $errmsg );
            }else{
                #celebrate
                echo '<h3>That is acceptable</h3>';
            }
        }
    }
?>

暂无
暂无

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

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