草庐IT

javascript - 根据网络表单单选按钮选择显示结果 div

coder 2024-04-24 原文

我想简单地 .show() 一个基于网络表单单选按钮(用户)选择的 div

为简洁起见,让我们看下面(但请注意,我正在寻找一些可扩展的建议,因为我的网络表单将有 7 个问题和 5 个答案。我有 5 个结果 divs)

Note:// 所以,基本上会有7个问题,每个问题5个答案。所以我需要一个数组,通过用户单选按钮选择包含 5 个可能的答案组合,最好使用输入“value”字段;所以我可以简单地更改值组合的值等于什么 div 结果屏幕。 div 结果屏幕将只是 div 中的 5 组独特内容,仅此而已。


标记:

<div class="page1">
  <form class="sampler">
    <input type="radio" name="sex" value="male" checked>Male
    <br>
    <input type="radio" name="sex" value="female">Female
  </form>
</div>

<div class="page2">
  <form class="sampler">
    <input type="radio" name="food" value="tacos" checked>Tacos
    <br>
    <input type="radio" name="food" value="spicynuts">Rotten Spicy Peanuts
  </form>
</div>

<div id="resultsONE"><!-- one results div is display none by default sample but there would be much more content here  -->
  <p>Congratulations, you are NOT the father</p>
</div>

我知道下面的语法很糟糕;但这是我考虑从 JS 开始的逻辑。请注意,我将有 5 个独特的结果 #divs


function resultsdivONE () { 
  if ($input value == "male" & "tacos") {
    $('#resultsONE').show();   
  } else if () {
    // do
  } else {
    // do
  }
}

正如我上面提到的;我正在寻找一种方法,我可以简单地使用 SELECTED 输入 value="";因此可以稍微轻松地更改它们。

示例。


if ("male" & "tacos" & "nextanswer" & "nextanswerafter") { // etc up to 7
   $('#resultsONE').show(); 
 }  // first results div

可能对 php 选项开放。

感谢您的关注!

最佳答案

根据网络表单单选按钮选择显示结果 div

要实现什么?

所以基本上,所寻求的是一个包含单选按钮和结果的简单表格,该表格应与单选选项的组合相匹配。根据问题,问题应该易于维护和更改,而不必总是触及脚本或其初始逻辑。 这投票支持将问题和逻辑外包 - 将其与 DOM 分开。

如何实现?

问题标签中很快提到并进一步可见的是 php 和 ajax。鉴于可能希望将问题完全外包并通过 ajax 从 php 中获取它们。 再次投票支持外包。

实现该目标需要什么?

  • 是否需要任何框架和/或库?不一定,但可能有用
    • 检索 JSON
    • 创建 DOM 元素
  • 我们是否始终需要 DOM 中的所有问题和答案?不是真的

For brevity lets take below (but note I'm looking for somewhat scaleable advice as my web form will have 7 questions and 5 answers each. And I have 5 results divs)

  1. 我建议动态创建 DOM,因为 - 直到现在 - 没有理由一直保留它,它会使 HTML 文件本身看起来更简洁。
  2. 此外,可以将布局、结构、逻辑和数据分开,最终允许您通过更改一个文件来更改答案和问题。
  3. 使用这样的方法,您可以使用相同的代码创建更多包含不同问题的表单。
  4. 如果您还没有使用任何库/框架,请不要只为这个脚本添加一个。

结论

为了使其易于维护,问题和答案将外包到一个 json 文件中(此处为 JSON.js)。鉴于此,也可以通过 php 或任何网络服务检索它和/或将它们存储在数据库中。此外,还提供了创建具有不同问题的多个表单的可能性,这些表单都使用相同的代码。

There is a Fiddle available for it

代码

<html>
    <head>
        <!-- optional styles -->
        <style>
            #Container{
                left: 50%;
                position: absolute;
                text-align: center;
                top: 50%;
                transform: translate(-50%, -50%);
            }
        </style>

        <script>
            //This is out simple AJAX routine to not overload it by any framework.
            //If you are already using jQuery, just use $.get()
            ;var AJAX = {
                getXmlDoc: function(){return ((window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"))},

                //u:=url, f:=callback, c:=any param to pass to callback
                Get: function(u, f, c){
                    var tDoc = this.getXmlDoc();

                    tDoc.open('GET', u, true);
                    tDoc.onreadystatechange = function(){
                        if (tDoc.readyState === XMLHttpRequest.DONE && tDoc.status === 200) f(tDoc, c);
                    };

                    tDoc.send();
                }
            };

            //This is going to be the namespace holding our functionality.
            //In the end one should outsource this to a script file, yet we leave it here in the example for a better overview.
            ;var Quiz = {
                mContainer: null, //In this container the quiz gets created in
                mCurrent: null, //Stores the current displayed question
                mJSON: null, //In here we are going to store the JSON result

                //Handling logical errors, like missing data or json
                _Error: function(m){
                    console.log(m)
                },

                //The event called on the radio change event
                //e:=element
                _onChange: function(e){
                    if (e && this.mJSON.questions[this.mCurrent]){
                        //We are going to those the result of this question in the JSON
                        this.mJSON.questions[this.mCurrent].value = e.value;

                        //If the question is not the last, we are going to display the next one
                        if (this.mCurrent < this.mJSON.questions.length - 1){
                            this.hideQuestions();
                            this.showQuestion(this.mCurrent + 1)
                        }
                        else{
                            //Else we are going to show the result
                            this.hideQuestions();
                            this.showResult()
                        }
                    }
                    else this._Error('_onChange(): Invalid parameters')
                },

                //The function to initialise our quiz.
                //We are going to grab the json data and analyse it.
                //c:=container element || document.body, l:=link || 'JSON.js'
                Init: function(c, l){
                    this.mContainer = (c || document.body);

                    var tL = (l || 'JSON.js');
                    AJAX.Get(tL, function(r, l){
                        Quiz.mJSON = JSON.parse(r.response);

                        if (Quiz.mJSON && Quiz.mJSON.questions)
                            Quiz.showQuestion(0)
                        else
                            Quiz._Error('Init(): No questions found with "' + l + '"')
                    }, tL)
                },

                //Hiding the previously asked questions (remove from dom)
                hideQuestions: function(){
                    while(this.mContainer.firstChild) this.mContainer.removeChild(this.mContainer.firstChild)
                },

                //Going to show the result according to the asked questions
                showResult: function(){
                    var tValues = []; //Storing our answers
                    for(var i=0, j=this.mJSON.questions.length; i<j; i++)
                        if (this.mJSON.questions[i].value) tValues.push(this.mJSON.questions[i].value)

                    //Going to store the result text
                    var tResult = 'No match for ' + tValues.join(',');

                    //Looping through all requirements to get a match
                    for(var i=0, j=this.mJSON.answers.length; i<j; i++){
                        //The requirements which need to match the values
                        var tR = this.mJSON.answers[i].requirement;

                        //For this we filter all the elements which do not match the requirements
                        var tF = tValues.filter(function(e){return tR.indexOf(e) === -1})

                        //If that list is empty, all elements matched and we can stop
                        if (!tF || tF.length === 0){
                            tResult = this.mJSON.answers[i].message;
                            break;
                        }
                    }

                    //Now we are going to dislpay the result
                    var tH = document.createElement('h1');
                    tH.innerHTML = tResult;
                    this.mContainer.appendChild(tH)
                },

                //This creates and shows a question of our question array
                //i:=JSON.questions array index
                showQuestion: function(i){
                    if (i >= 0 && i<this.mJSON.questions.length){
                        this.mCurrent = i;

                        var tQ = this.mJSON.questions[i];
                        var tN = Object.getOwnPropertyNames(tQ)[0]; //The property name is going to become the radio group name

                        //We are going to create a title (h1) and multiple radios (input & label) for each question
                        var tF = document.createDocumentFragment();

                        //Creating the header
                        var tH = document.createElement('h1');
                        tH.innerHTML = tQ.label;
                        tF.appendChild(tH);

                        //Creating the questions
                        for(var i=0, j=tQ[tN].length; i<j; i++){
                            var tR = document.createElement('input');
                            tR.type = 'radio';
                            tR.value = tQ[tN][i];
                            tR.name = tN;
                            tR.onchange = function(){Quiz._onChange(this)};
                            tF.appendChild(tR);

                            var tL = document.createElement('label');
                            tL.for = tR.name;
                            tL.innerHTML = tR.value;
                            tF.appendChild(tL);
                        }

                        //Now we are going to assign it to the dom.
                        this.mContainer.appendChild(tF)
                    }
                    else{
                        this.mCurrent = null;
                        this._Error('showQuestion(' + i.toString() + '): No such question loaded')
                    }
                }
            };
        </script>
    </head>

    <body onload = "Quiz.Init(document.querySelector('#Container'))">
        <div id = 'Container'>
            <!-- Container for the quiz -->
        </div>
    </body>
</html>

和 JSON.js

{
    "questions": [
        {"sex": ["male", "female"], "label": "What are you?"},
        {"food": ["tacos", "spicynuts"], "label": "What do you eat?"},
        {"team": ["team a", "team b", "team rocket"], "label": "Where do you belong to?"}
    ],

    "answers": [
        {"requirement": ["male", "tacos", "team a"], "message": "one has chosen male, tacos and team a"},
        {"requirement": ["female", "tacos", "team a"], "message": "one has chosen female, tacos and team a"}
    ]
}

编辑:

在写我的建议时,我想到了一个小问题。鉴于您的解释“有七个问题和五个结果”。某些结果是共享结果还是没有?

变化

为了解决分享结果的问题,我想到了两种我认为输入和维护最简单的方式。

我们两次列出结果

这个解决方案可能听起来很傻而且太简单了。但它易于维护和管理。明显的缺点是缺乏数据完整性。

{"requirement": ["male", "spicynuts", "team a"], "message": "one has chosen male, spicynuts and team a"},
{"requirement": ["female", "spicynuts", "team a"], "message": "one has chosen male, spicynuts and team a"}

我们根据需求嵌套列表

另一种方法是嵌套需求(数组/对象中的数组),这样就可以简单地列出具有相同消息的更多需求。这里的失败是,即使一个人永远不需要它,也必须以这种方式构建它。

{
    "requirement": [
        ["male", "tacos", "team rocket"],
        ["male", "spicynuts", "team rocket"],
        ["female", "tacos", "team rocket"],
        ["female", "spicynuts", "team rocket"]
    ],
    "message": "team rocket rocks my socks!"
}

结论

最后我决定让用户决定并支持这两种方法以及初始和第二个解决方案的组合。可以像以前一样构造它,可以用相同的消息重复答案,也可以嵌套需求。

我们需要改变什么?

主代码文件中的一个函数

//Going to show the result according to the asked questions
showResult: function(){
    var tValues = []; //Storing our answers
    for(var i=0, j=this.mJSON.questions.length; i<j; i++)
        if (this.mJSON.questions[i].value) tValues.push(this.mJSON.questions[i].value)

    //Going to store the result text
    var tResult = 'No match for ' + tValues.join(',');

    //Looping through all requirements to get a match
    var tBreak = false; //We use this to double break both loops
    for(var i=0, j=this.mJSON.answers.length; i<j && !tBreak; i++){
        //The requirements which need to match the values
        var tR = this.mJSON.answers[i].requirement;

        //We put simple arrays in a nested array to keep the same logic/process
        var tRR = (typeof tR[0] === 'string') ? [tR] : tR;

        for(var k=0, l=tRR.length; k<l && !tBreak; k++){
            //For this we filter all the elements which do not match the requirements
            var tF = tValues.filter(function(e){return tRR[k].indexOf(e) === -1})

            //If that list is empty, all elements matched and we can stop
            if (!tF || tF.length === 0){
                tResult = this.mJSON.answers[i].message;
                tBreak = true;
            }
        }

        //If that list is empty, all elements matched and we can stop
        if (!tF || tF.length === 0){
            tResult = this.mJSON.answers[i].message;
            break;
        }
    }

    //Now we are going to dislpay the result
    var tH = document.createElement('h1');
    tH.innerHTML = tResult;
    this.mContainer.appendChild(tH)
},

这是用于测试的示例 JSON

{
    "questions": [
        {"sex": ["male", "female"], "label": "What are you?"},
        {"food": ["tacos", "spicynuts"], "label": "What do you eat?"},
        {"team": ["team a", "team b", "team rocket"], "label": "Where do you belong to?"}
    ],

    "answers": [
        {"requirement": ["male", "tacos", "team a"], "message": "one has chosen male, tacos and team a"},
        {"requirement": ["female", "tacos", "team a"], "message": "one has chosen female, tacos and team a"},

        {"requirement": ["male", "spicynuts", "team a"], "message": "one has chosen male, spicynuts and team a"},
        {"requirement": ["female", "spicynuts", "team a"], "message": "one has chosen male, spicynuts and team a"},

        {
            "requirement": [
                ["male", "tacos", "team rocket"],
                ["male", "spicynuts", "team rocket"],
                ["female", "tacos", "team rocket"],
                ["female", "spicynuts", "team rocket"]
            ],
            "message": "team rocket rocks my socks!"
        }
    ]
}

关于javascript - 根据网络表单单选按钮选择显示结果 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31146808/

有关javascript - 根据网络表单单选按钮选择显示结果 div的更多相关文章

  1. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. ruby-on-rails - 使用 Sublime Text 3 突出显示 HTML 背景语法中的 ERB? - 2

    所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择

  4. ruby-on-rails - link_to 不显示任何 rails - 2

    我试图在索引页中创建一个超链接,但它没有显示,也没有给出任何错误。这是我的index.html.erb代码。ListingarticlesTitleTextssss我检查了我的路线,我认为它们也没有问题。PrefixVerbURIPatternController#Actionwelcome_indexGET/welcome/index(.:format)welcome#indexarticlesGET/articles(.:format)articles#indexPOST/articles(.:format)articles#createnew_articleGET/article

  5. ruby - 如何在 Rails 4 中使用表单对象之前的验证回调? - 2

    我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser

  6. ruby - 如何根据特征实现 FactoryGirl 的条件行为 - 2

    我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden

  7. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  8. ruby-on-rails - Nokogiri:使用 XPath 搜索 <div> - 2

    我使用Nokogiri(Rubygem)css搜索寻找某些在我的html里面。看起来Nokogiri的css搜索不喜欢正则表达式。我想切换到Nokogiri的xpath搜索,因为这似乎支持搜索字符串中的正则表达式。如何在xpath搜索中实现下面提到的(伪)css搜索?require'rubygems'require'nokogiri'value=Nokogiri::HTML.parse(ABBlaCD3"HTML_END#my_blockisgivenmy_bl="1"#my_eqcorrespondstothisregexmy_eq="\/[0-9]+\/"#FIXMEThefoll

  9. ruby - 用 Ruby 编写一个简单的网络服务器 - 2

    我想在Ruby中创建一个用于开发目的的极其简单的Web服务器(不,不想使用现成的解决方案)。代码如下:#!/usr/bin/rubyrequire'socket'server=TCPServer.new('127.0.0.1',8080)whileconnection=server.acceptheaders=[]length=0whileline=connection.getsheaders想法是从命令行运行这个脚本,提供另一个脚本,它将在其标准输入上获取请求,并在其标准输出上返回完整的响应。到目前为止一切顺利,但事实证明这真的很脆弱,因为它在第二个请求上中断并出现错误:/usr/b

  10. 报告回顾丨模型进化狂飙,DetectGPT能否识别最新模型生成结果? - 2

    导读语言模型给我们的生产生活带来了极大便利,但同时不少人也利用他们从事作弊工作。如何规避这些难辨真伪的文字所产生的负面影响也成为一大难题。在3月9日智源Live第33期活动「DetectGPT:判断文本是否为机器生成的工具」中,主讲人Eric为我们讲解了DetectGPT工作背后的思路——一种基于概率曲率检测的用于检测模型生成文本的工具,它可以帮助我们更好地分辨文章的来源和可信度,对保护信息真实、防止欺诈等方面具有重要意义。本次报告主要围绕其功能,实现和效果等展开。(文末点击“阅读原文”,查看活动回放。)Ericmitchell斯坦福大学计算机系四年级博士生,由ChelseaFinn和Chri

随机推荐