使用单选按钮创建一个html表单,打开一个可选的输入文本字段

时间:2011-07-20 08:44:19

标签: forms html

我想写一个带有单选按钮的表单,打开一个可选的输入文本字段。

e.g。单选按钮:你有妻子/丈夫吗?如果用户说是输入字段dd,mm和yyyy出现(对于妻子/丈夫的生日,月和年)并且必须为要提交的表单写入正确的值(01加12加1978即被接受但不是1a加yy加上1945年)。

如果用户对问题回答“否”,则此字段没有理由显示(没有妻子/丈夫表示没有妻子/丈夫生日)并且传输了默认值dd,mm,yyyy。

我知道如何使用单选按钮的onClick事件上的style属性使div可见,但我不知道如何使输入字段对于是答案是必需的,对于无答案是可选的(实际上不可见)并且将传输默认值)。

2 个答案:

答案 0 :(得分:2)

我找到了一种非常简单的方法。

我感兴趣的代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Sample</title>

</head>
<body>
<script type="text/javascript">
function aff_div(ladiv) {
  document.getElementById(ladiv).style.display = "inline";
}

function cach_div(ladiv) {
  document.getElementById(ladiv).style.display = "none";
}

function affich_conj() {
  if (document.forms.devis.votconj[0].checked == true) {
    aff_div("ssconj");
  }

  if (document.forms.devis.votconj[1].checked == true) {
    document.getElementById("jj").value = 0;
    document.getElementById("mm").value = 0;
    document.getElementById("aaaa").value = 0;
    cach_div("ssconj");
  }
}
</script>
<form id="devis" name="devis" action="Validation-du-formulaire.php" method="post">

  <label>Do you have a wife/husband ?</label>
  <input type="radio" name="votconj" value="yes" onclick="affich_conj();">yes
  <input type="radio" name="votconj" value="no" checked="checked" onclick="affich_conj();">no

  <div id="ssconj">
    <p>
      <label>Her/his birthdate :</label>
      <select name="jj" id="jj">
        <option value="0" selected="selected">--</option>
        <option value="01">01</option>
        <option value="02">02</option>
      </select>
      <select name="mm" id="mm">
        <option value="0" selected="selected">--</option>
        <option value="01">01</option>
        <option value="02">02</option>
      </select>
      <select name="aaaa" id="aaaa">
        <option value="0" selected="selected">--</option>
        <option value="1993">1970</option>
        <option value="1992">1969</option>
      </select>
    </p>
  </div>

</form>

<script type="text/javascript">
  cach_div("ssconj");
</script>

</body>
</html>

答案 1 :(得分:0)

使用点击事件后显示的 class =“required”创建自定义输入字段。但是,如果您在点击收音机之前输入输入,只需在输入中添加类名必需。您可以使用 id =“test”向元素添加新类,如下所示:

$(document).ready(
      function(){
             $('#testRadio').click(function(){
                  $('test').addClass("required");
      });
});

现在验证类名为必需的输入元素。

您可以根据需要禁用/启用或显示/隐藏元素!

如果通过撰写 return false;

必需的输入未完全填写,请停用提交内容