我想简单地 .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 选项开放。
感谢您的关注!
最佳答案
所以基本上,所寻求的是一个包含单选按钮和结果的简单表格,该表格应与单选选项的组合相匹配。根据问题,问题应该易于维护和更改,而不必总是触及脚本或其初始逻辑。 这投票支持将问题和逻辑外包 - 将其与 DOM 分开。
问题标签中很快提到并进一步可见的是 php 和 ajax。鉴于可能希望将问题完全外包并通过 ajax 从 php 中获取它们。 再次投票支持外包。
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)
为了使其易于维护,问题和答案将外包到一个 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>
{
"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/
我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格: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
我主要使用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
所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择
我试图在索引页中创建一个超链接,但它没有显示,也没有给出任何错误。这是我的index.html.erb代码。ListingarticlesTitleTextssss我检查了我的路线,我认为它们也没有问题。PrefixVerbURIPatternController#Actionwelcome_indexGET/welcome/index(.:format)welcome#indexarticlesGET/articles(.:format)articles#indexPOST/articles(.:format)articles#createnew_articleGET/article
我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务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
我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden
我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c
我使用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
我想在Ruby中创建一个用于开发目的的极其简单的Web服务器(不,不想使用现成的解决方案)。代码如下:#!/usr/bin/rubyrequire'socket'server=TCPServer.new('127.0.0.1',8080)whileconnection=server.acceptheaders=[]length=0whileline=connection.getsheaders想法是从命令行运行这个脚本,提供另一个脚本,它将在其标准输入上获取请求,并在其标准输出上返回完整的响应。到目前为止一切顺利,但事实证明这真的很脆弱,因为它在第二个请求上中断并出现错误:/usr/b
导读语言模型给我们的生产生活带来了极大便利,但同时不少人也利用他们从事作弊工作。如何规避这些难辨真伪的文字所产生的负面影响也成为一大难题。在3月9日智源Live第33期活动「DetectGPT:判断文本是否为机器生成的工具」中,主讲人Eric为我们讲解了DetectGPT工作背后的思路——一种基于概率曲率检测的用于检测模型生成文本的工具,它可以帮助我们更好地分辨文章的来源和可信度,对保护信息真实、防止欺诈等方面具有重要意义。本次报告主要围绕其功能,实现和效果等展开。(文末点击“阅读原文”,查看活动回放。)Ericmitchell斯坦福大学计算机系四年级博士生,由ChelseaFinn和Chri