仅当选择了多个选择选项之一时,才要求填写输入字段


Require input field to be filled only if one of multiple select options selected

我有一个带有SELECT和TEXT(以及其他)输入的表单。 选择有两个选项。 其中一个选项要求将日期添加到文本框中,另一个选项不需要日期。

如果选择了其中一个表单选项,我需要找到一种方法来要求完成 TEXT 输入(这是一个 jquery 日期选择器),但另一个不需要它。

形式...

<input class="ml-text" type="text" name="descriptive_title" size="45" placeholder="Required ..." value="<? echo $doc_title; ?>"required>
        <br><br>
        <label class="title">Upload Type</label>
        <select class= "ml-select" name="upload_type">
                <option value="cutting_list">Cutting List</option>
                <option value="site_instruction">Extra Works</option>
                </select>
    <input class="ml-text" type="text" size="22" name="date_required" id="datepicker" placeholder="Date Required">

我尝试在处理表单的页面上使用标题来做到这一点,但与所有标题一样,特别是在同一页面上使用两个标题,它似乎在执行其他任何操作之前先抓住它们。

我试过了。。。

if($upload_type == 'cutting_list' && !isset($POST['date_required'])){
            $desc_title = str_replace(' ', '_', $descriptive_title);
            header( "Location: ../workflow/workflow.php?error=no_date&doc_title=$desc_title&department=$department");
    }
else {
     .... do everything else
header( "Location: ../workflow/workflow.php ");
}

如果上传类型是剪切列表,但日期 POST 未设置(也尝试过 !empty),那么它将返回表单并显示错误,但如果不满足这些条件,将继续使用脚本并返回表单,现在提交时标题中没有错误内容。

只是无法让它工作。

你可以

用javascript/jQuery检查select的值(https://api.jquery.com/change/),如果它是具有所需日期时间的日期,则可以将required(https://www.w3.org/TR/html5/forms.html#the-required-attribute)属性添加到input

小型示例脚本,如果选择了值1,则将输入设置为必需。

<html>
<body>
<select onchange="if (this.options[this.selectedIndex].value == '1') {document.getElementById('myinput').setAttribute('required', '');} else {document.getElementById('myinput').removeAttribute('required')}">
  <option value=''>none</option>
  <option value=1>1</option>
  <option value=2>2</option>
 </select>
<input type='text' id='myinput'>
</body>
</html>