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

时间:2016-02-19 14:43:37

标签: php html forms

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

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

表格......

<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没有设置(也试过!空),那么它会返回到有错误的表单,但是如果这些条件不符合,则会进行使用脚本并返回到表单,现在提交时没有标题中的错误内容。

无法让它发挥作用。

1 个答案:

答案 0 :(得分:2)

您可以使用javascript / jQuery查看select的值 (https://api.jquery.com/change/)如果是具有所需日期时间的那个,则可以将requiredhttps://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>