使用javascript创建调查表单

时间:2017-03-27 15:25:47

标签: javascript jquery

我有一个项目,我需要能够制作一份调查表。我试图模仿google表单的工作方式,其中最初只显示调查标题的输入框,以及"添加问题"按钮位于底部。

当"添加问题"单击按钮,将出现需要输入问题的输入框。然后在问题的输入框下方,三个radiobox会出现标记为单选框,复选框和文本。这是为了选择问题的选择类型。单选框用于多选类型问题,复选框用于包含多个答案的问题,而文本用于无法选择的问题。

单击radiobox或复选框后,将显示两个输入框以供选择。还会有一个名为&#34的按钮;添加选项"如果调查创建者希望为表单添加更多选项,则在最后一个选项输入框下。但是,如果单击文本选项,则不应显示选项的输入框(或者如果最初选择了radiobox或复选框,则选项的输入框将消失)。

我的问题是,如果我针对前几个问题单击radiobox / checkbox选项,然后为下一个问题选择文本,那么当文本框不应该出现时,选项的输入框仍会显示。如果我在前几个问题中选择了文本,虽然选择最初不会出现,但是当我选择radiobox或复选框时,选择的输入框会显示在前面的问题下面,其中所选答案类型是以前不存在的文本。

这是代码的html部分:

<div class="container" style="margin-top: 5%">
        <div class="row">
            <div class="col-md-12">
                <div class="panel panel-default">
                    <div class="panel-heading">Create New Survey:</div>
                        <div class="panel-group">
                            <form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST" class="form-control" style="height: 700px; border: none" id="survey-form">
                                <label>Survey Title: </label>
                                    <input name="survey_title" id="survey_title" type="text" class="form-control input-group"/>
                                    <input name="qnum" id="qnum" type="hidden" value=""/>
                                    <input name="choicenum" id="choicenum" type="hidden" value=""/>
                                <label>Survey Questions:</label>
                                <div id="questions">
                                </div>
                                <button class="btn btn-primary" type="button"style="display: block; margin-top: 5px;" id="addq"><span class="glyphicon glyphicon-plus"></span>Add a question</button>
                                    <button class="btn btn-success" type="submit" id="uploadsurvey" name="uploadsurvey" style="display: block; margin-top: 10px">Upload Survey</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>

这是js部分:

    $(document).ready(function(){
    var i=0;
    var numOfQuestions=0;
    var choice_c = 1;
    $("#addq").click(function(){
            numOfQuestions++;
            i++;
            $("#questions").append("<div id='newq' style='margin-top: 5px; margin-bottom: 5px'></div>");
            $("#newq").append("Question: <input type='text' name='q"+i+"' class='form-control' style='display: inline-block' id='q"+i+"'/>");
            $("#qnum").attr("value", numOfQuestions);
            $("#newq").append("<label><input type='radio' name='radio"+i+"' value='radio' class='choices radiobox' id='radiobox"+i+"'/>&nbsp;Radiobox&nbsp;&nbsp;</label>");
            $("#newq").append("<label><input type='radio' name='radio"+i+"' value='check' class='choices checkbox' id='checkbox"+i+"'/>&nbsp;Checkbox&nbsp;&nbsp;</label>");
            $("#newq").append("<label><input type='radio' name='radio"+i+"' value='text' class='choices textbox' id='textbox"+i+"'/>&nbsp;Text&nbsp;&nbsp;</label>");
            $("#newq").append("<input type='text' class='form-control qchoice' name='radiochoice"+choice_c+"_q"+i+"' id='radiochoice"+choice_c+"' title='q"+i+"' style='display: none'/>");
            choice_c++;
            $("#newq").append("<input type='text' class='form-control qchoice' name='radiochoice"+choice_c+"_q"+i+"' id='radiochoice"+choice_c+"' title='q"+i+"' style='display: none'/>");
            choice_c++;
            $("#newq").append("<button id='radiobtn"+i+"' type='button' class='btn btn-primary add-radio-choice' style='display: none'><span class='glyphicon glyphicon-plus'></span>Add choices</button>");
            $("#newq").append("<button id='checkbtn"+i+"' type='button' class='btn btn-primary add-checkbox-choice' style='display: none'><span class='glyphicon glyphicon-plus'></span>Add choices</button>");
        });
        $(document.body).on('change', '.choices' ,function() {
            if ($(".radiobox").is(":checked")) {
                $(".add-radio-choice").show();
                $(".qchoice").show();
                $(".add-checkbox-choice").hide();
            }
            else if ($(".checkbox").is(":checked")) {
                $(".add-checkbox-choice").show();
                $(".add-radio-choice").hide();
                $(".qchoice").show();
            }
            else if($(".textbox").is(":checked")){
                $(".add-checkbox-choice").hide();
                $(".add-radio-choice").hide();
                $(".qchoice").hide();
            }
        });
        $(document.body).on('click', '.add-radio-choice' ,function(){
            $("#newq").append("Choice: <input type='text' name='radiochoice"+choice_c+"_q"+i+"' title='q"+i+"' class='form-control qchoice' id='radiochoice"+choice_c+"'/>");
            $("#choicenum").attr("value", choice_c);
        });
        $(document.body).on('click', '.add-checkbox-choice' ,function(){
            $("#newq").append("<input type='text' name='radiochoice"+choice_c+"_q"+i+"' title='q"+i+"' class='form-control qchoice' id='checkboxchoice"+choice_c+"'>");
            $("#choicenum").attr("value", choice_c);
        });
});

我还为这个here添加了一个小提琴:

我还应该添加一个动态删除表单中的选项和问题的选项,但我还不知道如何解决它...

1 个答案:

答案 0 :(得分:3)

嗯,首先,你的小提琴不包括jQuery或bootstrap CSS连接。但那是次要的。第二件事,你可能会把一切都放在一个函数中让自己感到困惑。相反,让子函数为您处理一些工作。

关于您在选择文字选项时仍然显示的广播问题,请查看下方或this fiddle。当用户选择不同的答案选项时,只需删除DOM结构以处理旧选项,并为新选项创建DOM结构。

我试图非常广泛地评论代码,应该相当清楚 - 但是如果你有他们的话就提出问题!

$(document).ready(function() {
  var i = 0;
  var numOfQuestions = 0;
  var labelEl = $("<label>");
  var inputEl = $("<input>");
  // Handle the user clicking on "Add a question"
  $("#addq").click(function() {
    // Increment both counters,
    numOfQuestions++;
    i++;
    // a nested function creates the HTML DOM structure.
    addQuestion();
    // Handle the user choosing what type of question they want
    $(".choices").on("change", function() {
      var option = $(this).val();
      switch (option) {
        case "radio":
          showRadioOpts();
          break;
        case "checkbox":
          showCheckboxOpts();
          break;
        case "text":
          showTextOpts();
          break;
      }
    })

  });

  /**
   * This handles the HTML DOM creation. I don't want to clog up
   *   the main routine with all the ugly, so I've moved it here.
   *   Purely cosmetic. The functioning is the same as the former
   *   append() functions with the element completely spelled out.
   **/
  function addQuestion() {

    var newQuestionEl = inputEl.clone().prop({
      "type": "text",
      "name": "q" + i,
      "id": "q" + i,
      "class": "form-control"
    });
    var newQuestion = labelEl.clone().prop({
      "for": "q" + i,
      "class": "form-control"
    }).append("Question: ", newQuestionEl);

    var newQTypeArr = [];
    var newQTypeRadioEl = inputEl.clone().prop({
      type: "radio",
      name: "qType" + i,
      id: "qType" + i,
      value: "radio",
      class: "choices radiobox"
    });
    newQTypeArr[0] = labelEl.clone().append(newQTypeRadioEl, " Radio");

    var newQTypeCheckEl = inputEl.clone().prop({
      type: "radio",
      name: "qType" + i,
      id: "qType" + i,
      value: "checkbox",
      class: "choices radiobox"
    });
    newQTypeArr[1] = labelEl.clone().append(newQTypeCheckEl, "Checkbox");
    var newQTypeTextEl = inputEl.clone().prop({
      type: "radio",
      name: "qType" + i,
      id: "qType" + i,
      value: "text",
      class: "choices radiobox"
    });
    newQTypeArr[2] = labelEl.clone().append(newQTypeTextEl, "Text");
    var answerOptionsEl = $("<div>").prop({
      class: "answer-options-pane"
    });
    var newAnsContainerEl = $("<div>").prop({
      class: "answer-pane"
    }).append(newQTypeArr, answerOptionsEl);
    var newQContainerEl = $("<div>").prop({
      id: "newq"
    }).append(newQuestion, newAnsContainerEl);

    $("#questions").append(newQContainerEl);
    $("#qnum").attr("value", numOfQuestions);
  }; //end addQuestion()

  // Toggle the radio answer options
  function showRadioOpts() {
    // First, hide all answer options. Then, add one radio option.
    $(".answer-options-pane").empty();
    addRadioOpts();

  }; // end showRadioOpts()

  // Toggle the checkbox answer options
  function showCheckboxOpts() {
    $(".answer-options-pane").empty();
  }; // end showCheckboxOpts() 

  // Toggle the text box answer options
  function showTextOpts() {
    $(".answer-options-pane").empty();
    addTextOpts();
  }; // end showTextOpts()

  /***
   * Another DOM element creation function. This creates the radio
   *   button text option, and if it's the first, a button to add
   *   more options. 
   ***/
  function addRadioOpts() {
    // We want to get the length of the current choices, 
    //  as this will give us an index for the new option
    
    var radioChoice = $(".radio-choice");
    var choice_c = radioChoice.length;
    var radioChoiceTextEl = inputEl.clone().prop({
      "type": "text",
      "class": "form-control answer-option radio-choice",
      "name": "radiochoice" + choice_c + "_q" + i,
      "id": "radiochoice" + choice_c + "_q" + i,
      "title": "q" + i
    });
    // If we don't have any radio elements yet, we will also
    //  want to create an "add more options" button.
    if (choice_c <= 0) {
      var addIconEl = $("<span>").prop({
        "class": "glyphicon glyphicon-plus"
      });
      var addChoiceButton = $("<button>").prop({
        "id": "radiobtn" + i,
        "class": "btn btn-primary add-radio-choice answer-option"
      }).append(addIconEl, "Add choices").on("click", function(evt) {
        // Make sure you don't let that button do what buttons do...
        evt.preventDefault();
        addRadioOpts()
      });
      $(".answer-options-pane").append(addChoiceButton);
    }
    radioChoiceEl = labelEl.clone().append(radioChoiceTextEl);
    // Make sure to add the new text element BEFORE the 
    //    add more button.
    $(".add-radio-choice").before(radioChoiceEl);
  };
  
  function addTextOpts(){
    var textChoiceTextEl = inputEl.clone().prop({
      "type": "text",
      "class": "form-control answer-option text-choice",
      "name": "radiochoice_q" + i,
      "id": "textchoice_q" + i,
      "title": "q" + i
    });
        textChoiceEl = labelEl.clone().append("Text: ", textChoiceTextEl);
    $(".answer-options-pane").append(textChoiceEl)
    }
});
label {
  display: block;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container" style="margin-top: 5%">
  <div class="row">
    <div class="col-md-12">
      <div class="panel panel-default">
        <div class="panel-heading">Create New Survey:</div>
        <div class="panel-group">
          <form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST" class="form-control" style="height: 700px; border: none" id="survey-form">
            <label>Survey Title: </label>
            <input name="survey_title" id="survey_title" type="text" class="form-control input-group" />
            <input name="qnum" id="qnum" type="hidden" value="" />
            <input name="choicenum" id="choicenum" type="hidden" value="" />
            <label>Survey Questions:</label>
            <div id="questions">
            </div>
            <button class="btn btn-primary" type="button" style="display: block; margin-top: 5px;" id="addq"><span class="glyphicon glyphicon-plus"></span>Add a question</button>
            <button class="btn btn-success" type="submit" id="uploadsurvey" name="uploadsurvey" style="display: block; margin-top: 10px">Upload Survey</button>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>
</div>