javascript – 显示基于Web表单单选按钮选择的结果div

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

为简洁起见,我们可以在下方(但请注意,我正在寻找一些可扩展的建议,因为我的网页表格将分别有7个问题和5个答案.我有5个结果div)

注意://所以,基本上会有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输入值=“”;所以它们可以很容易地改变.

例.

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

可能对PHP选项开放.

谢谢参观!

解决方法:

显示结果div基于Web表单单选按钮选择

要做什么?

基本上,所搜索的是一个包含单选按钮和结果的简单表单,它应该与无线电选择的组合相匹配.根据问题,问题应该易于维护和改变,而不总是触及脚本或其初始逻辑.
这投票支持外包问题和逻辑 – 将其与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)

>我建议动态创建DOM,因为 – 直到现在 – 没有理由一直保留它,这使得HTML文件本身看起来更加纤薄和整洁.
>此外,可以分离布局,结构,逻辑和数据,最终允许您通过更改一个文件来更改答案和问题.
>使用这样的方法,您可以使用不同的问题创建更多表单,但代码相同.
>如果您尚未使用任何库/框架,请不要仅为此脚本添加一个.

结论

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

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 onl oad = "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!"
        }
    ]
}

相关文章

IE6是一个非常老旧的网页浏览器,虽然现在很少人再使用它,但...
PHP中的count()函数是用来计算数组或容器中元素的个数。这个...
使用 AJAX(Asynchronous JavaScript and XML)技术可以在不...
Ajax(Asynchronous JavaScript and XML)是一种用于改进网页...
本文将介绍如何通过AJAX下载Excel文件流。通过AJAX,我们可以...
Ajax是一种用于客户端和服务器之间的异步通信技术。通过Ajax...