我有一个简单的HTML表格,表格中有一系列问题。如果用户对“是/否”单选按钮问题的回答为“是”,那么我想显示一个隐藏的行,使他们可以在textarea字段中输入详细信息。如果单击否,则应清除并再次隐藏文本区域输入。

这是我的html表单,上面有一个是/否问题,如果单击是,则有一个隐藏行以获取更多详细信息:

<form class="form-horizontal" action="#" method="post" id="questionForm">
      <input type="hidden" name="recid" value="1">

      <table class="table table-condensed table-hover table-bordered">

          <tr>
          <td><strong>Question 1</strong></td>
          <td>please answer yes or no to this question</td>
          <td>
              <div class="controls">
                  <label class="radio inline">
          <input type="radio" name="question1" id="question1" value="Yes" required>Yes        </label>
                  <label class="radio inline">
          <input type="radio" name="question1" id="question1" value="No" required>No          </label>
                  <label for="question1" class="error"></label>
        </div>
          </td>
          </tr>


          <tr class="question1yes">
          <td></td>
          <td>Please describe this and when it started</td>
          <td>
              <div class="controls">
          <textarea name="question1Details" rows="3"></textarea>
          <label for="question1Details" class="error"></label>
        </div>
          </td>
          </tr>

          </table>
</div>
                    <div class="control-group">
            <div class="controls">
              <button type="submit" class="btn btn-primary">Continue</button>
              <button type="reset" class="btn">Reset</button>
            </div>
        </div>

      </form>


这是我当前无法使用的脚本:

$().ready(function() {
        // validate the form when it is submitted
        $("#questionForm").validate();

        if($("#question1:checked").length != 0){
                    // yes is checked... show the dependent fields
                        $(".question1yes").show();
                    }else{
                        // hide it and blank the fields, just in case they have something in them
                        $(".question1yes").hide();
                        $("#question1Details").val("");
                    }


        $("#question1").click(function(){
                    // show the dependent fields
                    if(this.value == "Yes"){
                        $("#question1yes").show();
                    }else{
                        // hide the dependent fields and blank them
                        $(".question1yes").hide();
                        $("#question1Details").val("");
                    }
                    });

        });


我已经设置了一个jsFiddle here来演示我的表单。我的可选行从隐藏开始,但是当您单击“是”单选按钮时不可见。

最佳答案

您的无线电输入具有相同的ID,这不是有效的HTML。同样,这也破坏了代码,因为您不能独立地操作它们。

我的建议:

_y_n(或您喜欢的任何一种)分别添加到ID。 (或使用任何其他唯一ID)

将点击事件绑定到新ID。
码:

$("#question1_y").click(function () {
    $(".question1yes").show();
});

$("#question1_n").click(function () {
    $(".question1yes").hide();
    $(".question1yes textarea").val("");
});

09-10 11:11
查看更多