CSS Style Javascript - javascript

Im Making a question for a website and would like the the correct / try again messages in the var reltext to be different colours ie green for correct and red for wrong and maybe a small png beside each.
any ideas ?
<form name = "Q1">
<p>A local construction company has purchased 5 brand new diggers. Two of them have a telescopic jib. If a driver chooses a digger to use at random what is the probability it will have a telescopic jib?<br>
0/5
<input name = "rad1" type = "radio" class="radio" onclick = "getAnswer('1a', '1')">
1/5
<input name = "rad1" type = "radio" class="radio" onclick = "getAnswer('1b', '2')">
2/5
<input name = "rad1" type = "radio" class="radio" onclick = "getAnswer('1c', '3')">
3/5
<input name = "rad1" type = "radio" class="radio" onclick = "getAnswer('1d','4')">
<br><br>
</p>
<div id = "para"><div>
</form>
<script type = "text/javascript">
var reltext = [];
reltext[1] = "TRY AGAIN - 0/5 This would mean that there was no diggers with a telescopic jib."
reltext[2] = "TRY AGAIN - 1/5 This would mean that there was only 1 digger with a telescopic jib"
reltext[3] = "CORRECT - 2/5 This would mean that there was 2 diggers with a telescopic jib"
reltext[4] = "TRY AGAIN - 3/5 This would mean that there was 3 diggers with a telescopic jib."
function getAnswer(ans, rel) {
document.getElementById("para").innerHTML = reltext[rel];
if (ans == "1c") {alert ("Correct - Well done!")}
else {alert ("Incorrect - Try again")}
}
</script>

You may not style the contents of an alert box with JavaScript (or anything else for that matter).
A good alternative would be using a framework like jQuery UI and use modal dialogs instead of JS alerts. Here's a link to jQuery UI's dialogs: http://jqueryui.com/demos/dialog/

You could do this several ways.
1. You could replace your reltext with the following:
reltext[1] = "<div style='background-color:#dd0000;'>TRY AGAIN - 0/5 This would mean that there was no diggers with a telescopic jib.</div>"
reltext[2] = "<div style='background-color:#dd0000;'>TRY AGAIN - 1/5 This would mean that there was only 1 digger with a telescopic jib</div>"
reltext[3] = "<div style='background-color:#00dd00;'>CORRECT - 2/5 This would mean that there was 2 diggers with a telescopic jib</div>"
reltext[4] = "<div style='background-color:#dd0000;'>TRY AGAIN - 3/5 This would mean that there was 3 diggers with a telescopic jib.</div>"
2. Or you could setup a style for the div with id="para". Something like:
<style type="text/css">
.classWrong { bakcground-color: #dd0000; }
.classRight { background-color: #00dd00; }
</style>
and then in your script section change the function to set the style:
function getAnswer(ans, rel) {
document.getElementById("para").innerHTML = reltext[rel];
if (ans == "1c") {
document.getElementById("para").className = "classRight";}
alert ("Correct - Well done!");
else {
document.getElementById("para").className = "classWrong";}
alert ("Incorrect - Try again")}
}
3. As far as adding images to the response just add in an img element to your reltext. maybe like:
reltext[1] = "<div style='background-color:#dd0000;'>TRY AGAIN - 0/5 This would mean that there was no diggers with a telescopic jib.<img src='images/Wrong.png' /></div>"
reltext[3] = "<div style='background-color:#00dd00;'>CORRECT - 2/5 This would mean that there was 2 diggers with a telescopic jib<img src='images/Right.png' /></div>"
There are many other ways to do this but I thought I would just have a go at it.

To solve the issue the simplest way in my opinion is to make 2 div styles
Ex:
div.correct{
background-color: green;
}
div.wrong{
background-color: red;
}
make the reltext a multidimensional array, containing either the correct/wrong information, ex:
reltext[1][0] = "correct"
reltext[1][1] = "CORRECT - That answer is correct"
reltext[2][0] = "wrong"
reltext[2][1] = "WRONG - This is wrong!"
reltext[3][0] = "wrong"
reltext[3][1] = "WRONG - BLaBlah.."
and modify the function like:
function getAnswer(ans, rel) {
document.getElementById("para").innerHTML = reltext[rel][1];
document.getElementById("para").className = reltext[rel][0];

Related

Bringing Correct Message after correct answer

I am trying to create a message that shows "Correct" after user select a correct answer from options but I dont know why my code is not doing that. I have added the full code. After so many changes, I dont know why it is still not going through. The question and answer are in array of objects.
<script>
var questions = [{"category":"Science: Computers","type":"multiple","difficulty":"easy","question":"What does CPU stand for?","correct_answer":"Central Processing Unit","answers":["Central Process Unit","Computer Personal Unit", "Central Processing Unit", "Central Processor Unit"]},
{"category":"Science: Computers","type":"multiple","difficulty":"easy","question":"In the programming language Java, which of these keywords would you put on a variable to make sure it doesn't get modified?","correct_answer":"Final","answers":["Static", "Final", "Private","Public"]},
{"category":"Science: Computers","type":"boolean","difficulty":"easy","question":"The logo for Snapchat is a Bell.","correct_answer":"False","answers":["True", "False"]},
{"category":"Science: Computers","type":"boolean","difficulty":"easy","question":"Pointers were not used in the original C programming language; they were added later on in C++.","correct_answer":"False","answers":["True", "False"]},
{"category":"Science: Computers","type":"multiple","difficulty":"easy","question":"What is the most preferred image format used for logos in the Wikimedia database?","correct_answer":".svg","answers":[".svg", ".png",".jpeg",".gif"]},
{"category":"Science: Computers","type":"multiple","difficulty":"easy","question":"In web design, what does CSS stand for?","correct_answer":"Cascading Style Sheet","answers":["Counter Strike: Source","Corrective Style Sheet","Computer Style Sheet", "Cascading Style Sheet"]},
{"category":"Science: Computers","type":"multiple","difficulty":"easy","question":"What is the code name for the mobile operating system Android 7.0?","correct_answer":"Nougat","answers":["Ice Cream Sandwich", "Nougat", "Jelly Bean","Marshmallow"]},
{"category":"Science: Computers","type":"multiple","difficulty":"easy","question":"On Twitter, what is the character limit for a Tweet?","correct_answer":"140","answers":["120","160","100", "140"]},
{"category":"Science: Computers","type":"boolean","difficulty":"easy","question":"Linux was first created as an alternative to Windows XP.","correct_answer":"False","answers":["True", "False"]},
{"category":"Science: Computers","type":"multiple","difficulty":"easy","question":"Which programming language shares its name with an island in Indonesia?","answer":"Java","incorrect_answers":["Python","C","Jakarta", "Java"]}];
window.onload =function(){
var questionIndex = -1; // Not started
function submitAnswer() {
//document.body.innerHTML = '';
++questionIndex;
document.write(questions[questionIndex].question + "<br />");
for (var j=0; j < questions[questionIndex].answers.length; j++) {
document.write("<input type=radio id=myRadio name=radAnswer>" + questions[questionIndex].answers[j] + "<br />");
}
if (questionIndex < (questions.length - 1)) {
var nextButton = document.createElement("input");
nextButton.type = "button";
nextButton.value = "Submit Answer";
nextButton.addEventListener('click', submitAnswer);
document.body.appendChild(nextButton);
}
var userAnswer,
element = document.querySelector("#myRadio:checked");
if (element !== null) {
userAnswer = element.value;
} else {
userAnswer = null;
return "Select Answer"
}
if (userAnswer == questions[questionIndex].correct_answers) {
var message,
element = document.querySelector("#results");
if (element !== null) {
message = "Correct";
} else {
message = null;
return "Select Answer";
}
}
};
submitAnswer();
Everything is fine until this line:
document.body.appendChild(message);
You are trying to append a String value,but it's expecting a Node Object (i.e. parameter 1 is not of type 'Node'). Hence your code is not working properly.

Populating HTML with Javascript onload

I am trying to create a basic quizz webpage. I read some articles here, but most of the javascript code that I wrote I learned through books and video tutorials, so I am very confused with why they won't work. Here is the HTML:
<!DOCTYPE HTML>
<html>
<head>
<title>Quizz</title>
<script type = "text/javascript" src = "script.js"></script>
</head>
<body onload="init(); postaviPitanje();">
<div id="title">
<span> Quizz</span>
<div> <!--end title-->
<div id="form">
<form>
<fieldset>
<legend id="legend">
Question <span id="brPitanja"></span><!--span in wich a question number is sent-->
</legend>
<p id="pitanjeTxt"></p><!--question text field-->
<p><input type="radio" name="odgovor" id ="odg1" value ="1"/></p><!--question 1-->
<p><input type="radio" name="odgovor" id ="odg2" value ="2"/></p><!--question 2-->
<p><input type="radio" name="odgovor" id ="odg3" value ="3"/></p><!--question 3-->
<p><input type="radio" name="odgovor" id ="odg4" value ="4"/></p><!--question 4-->
</fieldset>
</form>
<div><!--end form-->
</body>
</html>
The Javascript code below is incomplete because it didn't even populate the first question on load. I was going to add additional logic afterwards, but as I'm stuck here, I didn't move past the initial function of the test version:
function init() {
//question number on start
var brojPitanja = 0;
//span with question No into a variable
var brPitanjaSpan = document.getElementById("brPitanja");
//p with question teks into a variable
var tekstPitanjaParagraph = document.getElementById("pitanjeTxt");
//radio buttons into variables
var radio1 = document.getElementById("odg1");
var radio2 = document.getElementById("odg2");
var radio3 = document.getElementById("odg3");
var radio4 = document.getElementById("odg4");
//question object initialization function
function pitanje (br, txt, a, b, c, d, t) { //br - question number;
//txt- question text;
//a, b, c, d - possible answers;
//t - int value for correct answer;
this.number = br;
this.text = txt;
this.answ1 = a;
this.answ2 = b;
this.answ3 = c;
this.answ4 = d;
this.correct = t;
}
//question objects
var p1 = new pitanje(1, "Whats my name?", "marko", "lazar", "perisa", "bogdan", 1);
var p2 = new pitanje(2, "How old I am?", "25", "24", "22", "21", 3);
//question array
var nizPitanja = new Array (p1, p2);
}
//setting question onto document
function postaviPitanje() {
var current = nizPitanja[brojPitanja]; //current cuestion
brPitanjaSpan.innerHTML = "" + brojPitanja; //place question number in question title
tekstPitanjaParagraph.innerHTML = current.text; //place question text in HTML
//fill radiobuttons with question text
radio1.innerHTML = current.answ1;
radio2.innerHTML = current.answ2;
radio3.innerHTML = current.answ3;
radio4.innerHTML = current.answ4;
}
The problem is that the page displays only that text that is already in HTML. I would appreciate any help as I'm just starting with Javascript, so I can't debug this myself. Also, I changed everything I could to English. Some things, like id values, I left as they were so I don't break it even more :)
As I said, I did read and learn from several sources, insluding stackoverflow, so if I missed any question that could help and made a double, I apologize in advance. And thanks in advance, also.
[EDIT] Here is the fiddle with edited code https://jsfiddle.net/uazntz1u/1/
Problem is you are defining your questions and answers array within init()
var nizPitanja = new Array (p1, p2);
this variable is scoped to the function itself(var) and won't be accessible anywhere outside.
Just declare it above init() so that postaviPitanje() can have access to it.
var nizPitanja=null;
init(); // Assign it inside init() without var.
postaviPitanje();
More about scope of variables here
What is the scope of variables in JavaScript?
Here is what I would suggest to do:
var quiz = (function () {
//question number on start
var brojPitanja = 0;
//span with question No into a variable
var brPitanjaSpan = document.getElementById("brPitanja");
//p with question teks into a variable
var tekstPitanjaParagraph = document.getElementById("pitanjeTxt");
//radio buttons into variables
var radio1 = document.getElementById("odg1");
var radio2 = document.getElementById("odg2");
var radio3 = document.getElementById("odg3");
var radio4 = document.getElementById("odg4");
//question object initialization function
function Pitanje (br, txt, a, b, c, d, t) {
//br - question number;
//txt- question text;
//a, b, c, d - possible answers;
//t - int value for correct answer;
// remark: change the lines below so that you
// have the same variable names like the parameters
this.number = br;
this.text = txt;
this.answ1 = a;
this.answ2 = b;
this.answ3 = c;
this.answ4 = d;
this.correct = t;
}
//question objects
var p1 = new Pitanje(1, "Whats my name?",
"marko", "lazar", "perisa", "bogdan", 1);
var p2 = new Pitanje(2, "How old I am?",
"25", "24", "22", "21", 3);
// you can remove this:
//question array
//var nizPitanja = new Array (p1, p2);
return {
brojPitanja : brojPitanja,
brPitanjaSpan : brPitanjaSpan,
textPitanjaSpan : textPitanjaParagraph,
radios : [radio1, radio2, radio3, radio4],
nizPitanja : [p1, p2]
}
})();
Now this is an Immediately-Invoked Function Expression (IIFE):
https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
It will return an object assigned to the variable quiz, which is your only global variable, so you don't pollute the global scope unnecessary with all the variables.
Now you can rewrite your function for making the questions:
function postaviPitanje() {
var current = quiz.nizPitanja[quiz.brojPitanja]; //current cuestion
quiz.brPitanjaSpan.innerHTML = "" + quiz.brojPitanja; //place question number in question title
quiz.tekstPitanjaParagraph.innerHTML = current.text; //place question text in HTML
//fill radiobuttons with question text
quiz.radios[0].innerHTML = current.answ1;
quiz.radios[1].innerHTML = current.answ2;
quiz.radios[2].innerHTML = current.answ3;
quiz.radios[3].innerHTML = current.answ4;
}
Regarding the radios you certainly know that the array index starts at 0, so the first radio button is radios[0], the second radios[1] and so on.
In your HTML file make the following changes:
<script type="text/javascript" src="script.js"></script>
<!-- add here these lines -->
<script type="text/javascript">
window.onload = postaviPitanje; // important: without braces
</script>
and change this:
<body onload="init(); postaviPitanje();">
to:
<body>
The whole code can be certainly refactored much better, but it would take long time to explain so many things. Since you said you're still beginner, this should give you some idea how to better organize your code.
EDIT:
There is one more issue in your HTML and JavaScript code: you are trying to access the property innerHTML of an input element of type radio. But this isn't possible. Change your code rather to:
<p>
<input type="radio" name="odgovor" id ="odg1" value ="1"/>
<label for="odg1" id="odg1_label"></label>
</p>
<p>
<input type="radio" name="odgovor" id ="odg2" value ="2"/>
<label for="odg2" id="odg2_label"></label>
</p>
<p>
<input type="radio" name="odgovor" id ="odg3" value ="3"/>
<label for="odg3" id="odg3_label"></label>
</p>
<p>
<input type="radio" name="odgovor" id ="odg4" value ="4"/>
<label for="odg4" id="odg4_label"></label>
</p>
And then get the labels in your JS-code:
var radio1 = document.getElementById("odg1_label");
var radio2 = document.getElementById("odg2_label");
var radio3 = document.getElementById("odg3_label");
var radio4 = document.getElementById("odg4_label");
Now it is possible to set the property innerHTML of the labels. That will result in placing the answer options ('marko', 'lazar', 'perisa', 'bogdan') where you want.

Looping through array using a button

Ok, in essence I want to create a short quiz that has a next and previous button. I want to loop through two arrays, questions and choices, and have a score at the end. I have read chapters on the DOM and Events and it is just not clicking apparently.
Really I need a little bit of code that shows a concrete example of how to manipulate the DOM. What I have so far are only the arrays, and a function declaring that x is in fact getting my element by id. haha.
Sorry I don't have more code to give. I tried to attach the id to a paragraph, and then get it by it's id and document.write the array, but that replaces the button. If you run the code below you'll see what I'm saying.
<!DOCTYPE html>
<html>
<head>
<title>Bom</title>
</head>
<body>
<input type="button" value="Iterate" id="myButton" onclick="iter_onclick()">
<p id="qArray">Some Text</p>
<script>
var qArray = ["Who is my dog?", "who is the prez?", "Who is my girlfriend?", "Who am I?"];
var cArray = [["Bill","Billy", "Arnold", "Tyler"],["Oz"," Buffon","Tupac","Amy"],["Tony Blair","Brack Osama","Barack Obama","Little Arlo"],["Emma Stone","Tony the Tiger","","The Smurf Girl"]];
function iter_onclick () {
var x = document.getElementById("qArray");
document.write("Hello World");
}
</script>
</body>
</html>`
Like I said, this is my first attempt at truly manipulating the DOM, and I know what I want to do. I just don't know how to do it. I am understanding all the syntax and events and objects and such. But, I'm not really sure how to apply it. Also, no Jquery. I want to know how to create applications with Javascript and then work my way into Jquery. Thanks people.
This will loop through your questions, hope this helps you to proceed.
var qArray = ["Who is my dog?",
"who is the prez?",
"Who is my girlfriend?",
"Who am I?"];
var cArray = [
["Bill", "Billy", "Arnold", "Tyler"],
["Oz", " Buffon", "Tupac", "Amy"],
["Tony Blair", "Brack Osama", "Barack Obama", "Little Arlo"],
["Emma Stone", "Tony the Tiger", "Amy Dahlquist", "The Smurf Girl"]
];
var index = 0;
function iter_onclick() {
//if this is the last question hide and displays quiz ends
if (index >= qArray.length) {
document.getElementById('qArray').innerHTML = '<div>Quiz End, Thank you</div>'
document.getElementById('myButton').style.visibility = 'hidden ';
return false;
}
var html = ' <div> ' + qArray[index] + ' </div> <div>';
for (var i = 0; i < cArray[index].length; i++) {
html += '<label><input type="radio" name="ans" value="'
+ cArray[index][i] + '"/ > ' + cArray[index][i] + ' </label>';
}
html += '</div > ';
document.getElementById('qArray').innerHTML = html;
index++;
}
Here's a very basic example you can work from. This modifies the existing DOM items. You cannot use document.write() on a document that is already loaded or it will clear everything you have and start over and it's not the most efficient way to put content into the DOM.
This example has a number of fields on the page, it loads a question and then checks the answer when you press the next button.
HTML:
<div id="question"></div>
<input id="answer" type="text"><br><br>
<button id="next">Next</button> <br><br><br>
Number Correct So Far: <span id="numCorrect">0</span>
Javascript (in script tag):
var qArray = ["Who is my dog?", "who is the prez?", "Who is my girlfriend?", "Who am I?"];
var cArray = [["Bill","Billy", "Arnold", "Tyler"],["Oz"," Buffon","Tupac","Amy"],["Tony Blair","Brack Osama","Barack Obama","Little Arlo"],["Emma Stone","Tony the Tiger","Amy Dahlquist","The Smurf Girl"]];
var questionNum = -1;
var numCorrect = 0;
function loadQuestion() {
++questionNum;
if (questionNum >= qArray.length) {
alert("all questions are done");
} else {
document.getElementById("question").innerHTML = qArray[questionNum];
document.getElementById("answer").value = "";
}
}
loadQuestion();
function checkAnswer() {
var answer = document.getElementById("answer").value.toLowerCase();
var allowedAnswers = cArray[questionNum];
for (var i = 0; i < allowedAnswers.length; i++) {
if (allowedAnswers[i].toLowerCase() == answer) {
return true;
}
}
return false;
}
document.getElementById("next").addEventListener("click", function(e) {
if (checkAnswer()) {
++numCorrect;
document.getElementById("numCorrect").innerHTML = numCorrect;
loadQuestion();
} else {
alert("Answer is not correct");
}
});
Working demo: http://jsfiddle.net/jfriend00/gX2Rm/

Set the value of multiple form elements with the same ID, Paypal

I'm trying to figure out a paypal issue.
I have multiple 'buy now' buttons on the page and I need to set a value for all of the buttons.
The 'buy now' button elements all have the same ids.
Each 'buy now' button represents a licence range, so there's '1-5', '6-10', '11-20, etc. I have a list of versions, they are dropped in the page as follows in a loop:
$strWeights1 .= "<span id='1".$row['Tag']."' onclick='select_weight(this.id)' class='linkoff'>". $row['Tag'] . "</span> | ";
I might be over thinking this, but what would be the best way to set the selected 'version' in all the 'buy now' buttons?
I am thinking of using the paypal variable 'item_number'
Cheers
Like I've said the buttons are from PayPal, I can't control the naming of there fields, hence the problem I'm up against.
OK, so the select weight function just makes the span work like a href tags, turning on and off the 'buttons'.
function select_weight(value){
value = value.substr(1);
document.forms["fontweight"]["fw"].value = value;
//this.forms["item_number"].value = value;
thin = document.getElementById('1Thin');
if(thin != null){
thin.className = "linkoff";
thin = document.getElementById('2Thin');
thin.className = "linkoff";
}
light = document.getElementById('1Light');
if(light != null){
light.className = "linkoff";
light = document.getElementById('2Light');
light.className = "linkoff";
}
book = document.getElementById('1Book');
if(book != null){
book.className = "linkoff";
book = document.getElementById('2Book');
book.className = "linkoff";
}
medium = document.getElementById('1Medium');
if(medium != null){
medium.className = "linkoff";
medium = document.getElementById('2Medium');
medium.className = "linkoff";
}
bold = document.getElementById('1Bold');
if(bold != null){
bold.className = "linkoff";
bold = document.getElementById('2Bold');
bold.className = "linkoff";
}
heavy = document.getElementById('1Heavy');
if(heavy != null){
heavy.className = "linkoff";
heavy = document.getElementById('2Heavy');
heavy.className = "linkoff";
}
black = document.getElementById('1Black');
if(black != null){
black.className = "linkoff";
black = document.getElementById('1Black');
black.className = "linkoff";
}
//alert(value);
fontweight1 = document.getElementById('1'+value);
fontweight2 = document.getElementById('2'+value);
fontweight1.className = "linkon";
fontweight2.className = "linkon";}
This is the code for the buttons, it is in the page about 16 times, the 'item_name' and 'hosted_button_id' change each time:
<form target=\"paypal\" action=\"https://www.paypal.com/cgi-bin/webscr\" method=\"post\" onsubmit=\"return validateForm()\" >
<input type=\"hidden\" name=\"cmd\" value=\"_s-xclick\">
<input type=\"hidden\" name=\"hosted_button_id\" value=\"xxxxxxxx\">
<input type=\"hidden\" name=\"item_name\" value=\"".$strProdName." : 1-5 terminals \">
<input type=\"hidden\" name=\"item_number\" value=\" [set this value] \">
<input type=\"image\" onMouseOver=\"this.src='images/paypalon.png';\" onMouseOut=\"this.src='images/paypaloff.png';\" src=\"images/paypaloff.png\" border=\"0\" name=\"submit\" alt=\"PayPal — The safer, easier way to pay online.\">
<input type='hidden' name='notify_url' value='http://ipn.php'>
</form>
I've been thinking about how to sort this out. Can I use the form validation function to access the specific form and set the value that way? I have been trying this with any success.
function validateForm(form)
{
var x=document.forms["fontweight"]["fw"].value;
if (x==null || x=="")
{
alert("Hold on a moment, you need to select a weight before hitting the ‘Buy’ button.");
return false;
}
else{
field = document.form;
//this.form['item_number'].value = x;
alert(field['item_name'].value);
return false;
}
}
the form tag has this call in it
onsubmit="return validateForm(this.form)"
Am I on the right track> or should I ditch it?
Ok, it looks like I've sorted this out. I've moved the validation to the button using 'onClick'. I'm passing (this.form) and using this to get to the element.
While I appreciate that multiple IDs with the same name is wrong, it's the PayPal buttons are are named the same not my code.

Changing a div's id in order to show/hide

My old code looked like this:
function unhide(rad) {
var id = "answer" + rad.id.replace("-", "");
var answer = document.getElementById(id);
if (answer) {
var current = document.getElementById(currentShown);
if (current) current.className = "hidden";
currentShown = id;
answer.className = "unhidden";
}
}
When my radio button was clicked:
<input class="editable" type="radio" name="q1" id="q1-a" onclick="unhide(this); scoreIncrement(this);"/>John
It would unhide this div:
<div id="answerq1a" class="hidden">
<p>Your answer is correct, John is 6ft2.</p>
</div>
But now, my radio button must look like this:
<input class="editable" type="radio" name="q1" id="untitled-region-1" onclick="unhide(this); scoreIncrement(this);"/>John
and my div that I want to unhide has the same id, but as they are unique, it replaces the 1 with the next number up. In my case it is 4 id's down so the id would be "untitled-region-5" for the new id, as follows:
<div id="untitled-region-5" class="hidden">
<p>Your answer is correct, John is 6ft2.</p>
</div>
So how can I change this code, to grab the new id "untitled-region-5" and minus 4 from it to fix it to the radio button with the new id's?
function unhide(rad) {
var id = "answer" + rad.id.replace("-", "");
var answer = document.getElementById(id);
if (answer) {
var current = document.getElementById(currentShown);
if (current) current.className = "hidden";
currentShown = id;
answer.className = "unhidden";
}
}
I am going along this sort of track:
function unhide2(rad) {
var id = $("div").attr('id').replace(/untitled-region-/, 'untitled-region-');
var untitled-region = document.getElementById(id);
if (untitled-region) {
var current = document.getElementById(currentShown);
if (current) current.className = "hidden";
currentShown = id;
untitled-region.className = "unhidden";
}
}
But I don't know how to replace the last digit on the id with "digit-4".
You've tagged this with jQuery, so I'll give you the jQuery answer.
The right way to solve this is not to mash about with id's, but to link the radio, and it's associated div some other way, and IMO the best way is using a data- attribute.
<input class="editable" type="radio"
name="q1" id="q1-a" data-answerId="untitled-region-5"/>John
Then your javascript becomes easy-as:
$('.editable').click(function(){
$('#' + currentShown).removeClass('unhidden').addClass('hidden');
var answerId = $(this).data('answerId');
$('#' + answerId).removeClass('hidden').addClass('unhidden');
});
Although I urge you to do away with the unhidden, hidden confusion and just use .show() and .hide()!

Categories

Resources