How to uncheck radio buttons after cloning html element with pure javascript? - javascript

Can't uncheck radio buttons after cloning a html element. Can anyone help me with this?
I tried .reset() .remove() and .checked=false but somehow it doesn't work.
<form>
<fieldset id="firstFieldset">
<legend>An advertiser wants to know if Shopping ads will appear on YouTube. What should you tell her?</legend>
<input type="radio" id="firstQuestionFirstOption" name="firstQuestion" value="firstQuestionFirstOption"> Shopping ads can only show on pre-roll video ads on YouTube<br>
<input type="radio" id="firstQuestionSecondOption" name="firstQuestion" value="firstQuestionSecondOption">Shopping Ads can only appear on Google.com<br>
<input type="radio" id="firstQuestionThirdOption" name="firstQuestion" value="firstQuestionThirdOption">Shopping ads can appear on Google Search partner websites like YouTube<br>
<input type="radio" id="firstQuestionFourthOption" name="firstQuestion" value="firstQuestionFourthOption">Shopping Ads can only appear on retail websites<br><br>
<button type="button" onclick="checkTheAnswerToTheFirstQuestion()">Show answer</button>
<p id="answerToTheFirstQuestion" onclick="checkTheAnswerToTheFirstQuestion();"></p>
<script>
function checkTheAnswerToTheFirstQuestion() {
if (document.getElementById('firstQuestionThirdOption').checked) {
document.getElementById('answerToTheFirstQuestion').innerHTML = "The answer is true";
} else {
document.getElementById('answerToTheFirstQuestion').innerHTML = "The answer is false";
var fieldset = document.getElementById("firstFieldset");
var newFieldset = fieldset.cloneNode(true);
}
}
</script>
</fieldset>
document.body.appendChild(newFieldset) = false;
</form>
<br><br>
<input type="button" value="Start again?" onClick="location.href=location.href">

You never actually add the thing you clone to the DOM, but the .checked = false method works in my example below. I've used .disabled = true since it seems more useful to show the answer you gave in the context of the response for reviewing what you previously answered.
In case I have made a wrong assumption, I left the .checked = false part commented.
I also cleaned up some of the radio input elements, as the you can simply set the right answer to "true" instead of having to maintain unique strings for all questions and possible answers.
I also made your function to check for answer more dynamic by allowing to give it the fieldset for the question rather being tied to a particular question.
This should give you a good understanding of adding/removing elements dynamically with JavaScript the way I think you are looking for.
<html lang="en">
<head>
<style>
.answerCorrect {
color: green;
}
.answerIncorrect {
color: red;
}
</style>
</head>
<body>
<form>
<fieldset id="firstFieldset">
<legend>An advertiser wants to know if Shopping ads will appear on YouTube. What should you tell her?</legend>
<input type="radio" name="firstQuestion" value="false"> Shopping ads can only show on pre-roll video ads on YouTube<br>
<input type="radio" name="firstQuestion" value="false">Shopping Ads can only appear on Google.com<br>
<input type="radio" name="firstQuestion" value="true">Shopping ads can appear on Google Search partner websites like YouTube<br>
<input type="radio" name="firstQuestion" value="false">Shopping Ads can only appear on retail websites<br><br>
<button class="answerButton" type="button" onclick="checkTheAnswer('firstFieldset')">Answer</button>
</fieldset>
</form>
<form id="answered">
</form>
<br/>
<input type="button" value="Start again?" onClick="location.href=location.href">
<script>
function checkTheAnswer(fieldsetId) {
// get a handle on the fieldset we are checking the answer for by its ID
let fieldset = document.getElementById(fieldsetId)
// was the checked value in the field set "true" (aka - correct)
let isCorrect = fieldset.querySelector("input[type='radio']:checked").value === "true"
// clone the answered fieldset
let newFieldset = fieldset.cloneNode(true)
// unset the radio buttons in a cloned fieldset
//newFieldset.querySelector("input[type='radio']:checked").checked = false
// disable the radio buttons in the 'answered' cloned fielset
let radios = newFieldset.querySelectorAll("input[type='radio']")
radios.forEach(r => r.disabled = true)
// remove the "Answer" button in the new fieldset
let answerButton = newFieldset.querySelector("button.answerButton[type='button']")
newFieldset.removeChild(answerButton)
// show the answer in the new fieldset
let answer = document.createElement("p")
answer.classList.add("answerText")
answer.classList.add(isCorrect ? "answerCorrect" : "answerIncorrect")
let answerText = document.createTextNode(`The answer is ${isCorrect ? "correct" : "incorrect"}.`)
answer.appendChild(answerText)
newFieldset.append(answer)
// get a handle on the form section used to put the cloned/answered fielsets into
let formAnswered = document.getElementById('answered')
// append the answered/reset fieldset into the 'answered' form
formAnswered.appendChild(newFieldset)
}
</script>
</body>

Related

Using Javascript to make certain fields disappear depending on dropdown value

I'm currently taking a beginner's course on Javascript. I just started coding about a week ago, and was given this prompt to use what I know so far to get data from forms etc.
I've run into a block, and the instructor told me I had to figure it out on my own but… I've been stuck on it for hours, just glancing at the materials and trying to search the internet for answers!! I know I have to use onchange, but I'm completely lost on the rest. I did the best that I could at this stage, but I'd really appreciate some help! Sorry for the super beginner/extra long question!
For the prompt, I was given a form and told to recreate it. After sorting out all the HTML, I have to:
Make sure everything starts out with no values.
Make sure the reset button works.
When choosing "male" in the "gender" category, the "hobby" row with "dance", "travel", and "photography" is hidden. The background color of the "soccer" and "futsal" row becomes blue.
When choosing "female" in the "gender" category, the "soccer" and "futsal" lines are hidden, and the background color of the "dance", "travel", "photography" line turns yellow.
When choosing "blank" from the "gender" category, both lines of "hobby" should be displayed, and the background color should be white.
Note: I don't think my HTML shows the rows for the "hobby" correctly, but it should be like:
- Soccer - Futsal
-Dance - Travel -Photography
<style>
h1 {
text-align: center;
}
.pink {
background-color: pink;
}
body {
border: 2px;
}
</style>
<script>
function clr() {
var t1 = document.info.lfname.value="";
var t2 = document.info.gender.value="";
var t3 = document.info.hobby.value="";
}
<p>Last name (Chinese):</p>
<form name="info">
<input type="text" name="lfname">
First name (Chinese):
<input type="text" name="lfname"><br>
<p>Last name (alphabet):</p>
<input type="text" name="lfname">
First name (alphabet):
<input type="text" name="lfname"><br><br>
Gender:
<select name="gender" onchange="hide()">
<option value=""></option>
<option value="man">Male</option>
<option value="woman">Female</option><br>
</select>
<p>Hobbies:</p>
<input type="checkbox" name="hobby" value="soccer">Soccer
<input type="checkbox" name="hobby" value="futsal">Futsal
<input type="checkbox" name="hobby" value="dance">Dance
<input type="checkbox" name="hobby" value="travel">Travel
<input type="checkbox" name="hobby" value="photo">Photography<br><br><br>
<input type="reset" class="pink" value="Reset" onclick="clr()">
<input type="submit" class="pink" value="Submit">
</form>
I'm avoiding giving you the full solution, so you can learn yourself but I have a few tips to put you in the right direction.
First you should make a css class hidden. This contains the following css
.hidden {
display:none
}
This is just to make your life a little easier.
You can get any element in javascript by adding an id as attribute, so for example:
HTML:
<input type="checkbox" name="hobby" value="soccer" id="soccer">
Javascript:
var HTMLelement = document.getElementById('soccer');
You can also add classes to elements in javascript
HTMLelement.classList.add("hidden");
As last tip, you can check whether the checked value is true or false. Based on this if structure add the class or not.
if ( HTMLelement.checked == true) {
do something
}
I hope this helps you, I will answers your comments if u have questions
Good luck!
As I see, most of the answers are giving you some hints, and that's ideal in your case as you supposed to do your homework by yourself, so I tried to push it further by giving you a working example, i'll comment each line of code to let you understand, but keep in mind I'll be using some advanced JavaScript stuff that requires digging into the JavaScript language in order to get more familiar with, and also you'd really have to search by yourself for how the methods/attributes that'll be using work in order to, firstly and most importantly to get some more knowledge in this language, and secondly to have answers for your teachers questions when they, probably, ask what do these things do.
Sorry for being little bit aggressive, here's a demo on how you'll get your job done.
// select the dropdown, male and female hobbies sections based on the IDs that we already gave to each one.
var gender = document.getElementById('gender'),
maleHobbies = document.getElementById('male-hobbies'),
femaleHobbies = document.getElementById('female-hobbies');
// adding change event listener to the dropdown.
gender.addEventListener('change', function() {
if(this.value === 'man') {
/**
* when 'Male' is selected on the dropdown(based on the value of the relevant checkbox):
* 1. add 'hidden' class to the female hobbies section to hide it.
* 2. remove the 'hidden' class from the male hobbies section to show it if it was hidden.
3. add the 'blue' class from the male hobbies section.
**/
femaleHobbies.classList.add('hidden');
maleHobbies.classList.remove('hidden');
maleHobbies.classList.add('blue');
} else if(this.value === 'woman') {
/**
* when 'Female' is selected on the dropdown(based on the value of the relevant checkbox):
* 1. add 'hidden' class to the male hobbies section to hide it.
* 2. remove the 'hidden' class from the female hobbies section to show it if it was hidden.
3. add the 'yellow' class from the female hobbies section.
**/
maleHobbies.classList.add('hidden');
femaleHobbies.classList.remove('hidden');
femaleHobbies.classList.add('yellow');
} else {
/**
* when the empty option is selected:
* remove the 'hidden' class from both the male and female hobbies sections.
* remove the 'blue' and 'yellow' classes from the male and female hobbies sections respectively.
**/
maleHobbies.classList.remove('blue', 'hidden');
femaleHobbies.classList.remove('yellow', 'hidden');
}
});
.pink {
background-color: pink;
}
/* 'hidden' class is used to hide an element by giving it a 'display' property of 'none'. */
.hidden {
display: none;
}
/* 'blue' class is used to make the male hobbies section background as blue */
.blue {
background-color: blue;
}
/* 'blue' class is used to make the female hobbies section background as yellow */
.yellow {
background-color: yellow;
}
<!--
I made some changes to your HTML:
- surrounded each checkbox inputs in a label tag with for attribute pointing to the corresponding input, soand you can click the text and the checkbox will check/uncheck.
- Added an ID to each checkbox input
- surrounded the corresponding checkboxes in a div, thus making row for male hobbies and row for female hobbies, each row(div tag) has a unique ID.
-->
<p>Last name (Chinese):</p>
<form name="info">
<input type="text" name="lfname" />
First name (Chinese):
<input type="text" name="lfname" /><br>
<p>Last name (alphabet):</p>
<input type="text" name="lfname" />
First name (alphabet):
<input type="text" name="lfname" /><br><br>
Gender:
<select name="gender" id="gender">
<option value=""></option>
<option value="man">Male</option>
<option value="woman">Female</option>
</select>
<p>Hobbies:</p>
<div id="male-hobbies">
<label for="soccer"><input type="checkbox" name="hobby" id="soccer" value="soccer" />Soccer</label>
<label for="futsal"><input type="checkbox" name="hobby" id="futsal" value="futsal" />Futsal</label>
</div>
<div id="female-hobbies">
<label for="dance"><input type="checkbox" name="hobby" id="dance" value="dance" />Dance</label>
<label for="travel"><input type="checkbox" name="hobby" id="travel" value="travel" />Travel</label>
<label for="photography"><input type="checkbox" name="hobby" id="photography" value="photo" />Photography</label>
</div>
<input type="reset" class="pink" value="Reset" />
<input type="submit" class="pink" value="Submit" />
</form>
Some hints for you:
you don't need to create a function that resets each input field as
the input[type="reset"](input with the type of reset) will do it
for you.
In order to make my demo work for you you have to either: paste the JavaScript code in a script tag and put that script just before </body>, or you can paste it in a seperate file then include it and again put the script tag that has the src to the file(that has the JavaScript code with .js extension) just before </body>.
And here are some useful links that may(indeed they'll do) help you:
Learn more more about getElementById method.
Learn more more about addEventListener method.
Learn more more about classList attribute and its methods(add, remove and more).
Hope I pushed you further.
Welcome to StackOverflow!
As it is for your course. It is intended to teach you something. So don't expect ready solution. I will give you some hints instead:
As someone mentioned in comments, you have missing closing HTML tags
<script>...your code here...</script>
As #ths mentioned, input is already self closing tag.
It is good practice (it sometimes depends on technology but for pure JS/HTML it is really good practice) to give HTML elements some unique IDs:
<input id="soccer" type="checkbox" name="hobby" value="soccer">Soccer
You can use
const soccerCheckbox = document.getElementById("soccer");
to obtain reference for some HTML elements, which you will use for further operations.
The easiest way to hide an element:
soccerCheckbox.hidden = true;
#Wimanicesir provided more elegant solution: https://stackoverflow.com/a/52630428/1944056
To append event listener:
const genderSelect= document.getElementById("gender");
genderSelect.onchange = function () {
//here you can show/hide appropriate elements
}
Another possibility: https://stackoverflow.com/a/4029360/1944056
To get the current value of dropdown:
document.getElementById("gender").value
It is important to enclose all your Javascript code into:
document.onload = function () {
...
}
To wait until all HTML elements are accessible
Good luck for your course!

Disabling a Form using Javascript under condition of "yes or no"

I have this form with Yes or No question in a radio button style to indicate whether such form has been filled out and submitted before. I want to disable this form using Javascript if the answer is "yes", per user's answer.
The "yes" would indicate that the form has already been submitted before and therefore re-filling out of the form is not allowed. This is to attempt to stop double or multiple submission.
Any advise will be greatly appreciated.
Dawn26
I might use an onchange function attached to the "Yes" radio button to either hide the form or remove it from the page altogether. Your markup might look similar to this:
<form id="formId">
<input type="radio" value="Yes" onchange="YourClass.disableForm()"/>
...
</form>
And the javascript:
var YourClass = function() {
return {
disableForm : function() {
document.getElementById("formId").setAttribute("style", "display: none;");
}
};
}();
You can create a function that disables all form controls other than the checkbox based on whether it's selected or not. This doesn't stop duplicate submission, so you will still need to handle that at the server. You can also hide the controls if you like, but just disabling them is probably sufficient.
You may also want to put up a message to explain why the form controls are disabled.
function checkDisabled(target) {
var form = target.form;
var elements = form.elements;
var disable = target.checked;
// Check every control in the form
for (var i=0, iLen=elements.length; i<iLen; i++) {
// Don't disable the checkbox
if (elements[i] != target) {
// Disable (or not) based on whether checkbox is checked
elements[i].disabled = disable;
}
}
}
Some test markup:
<label for="dateTime">Date and time<input id="dateTime" name="dateTime">
<br>
<span class="screenTip">YYYY-MM-DD hh:mm:ss</span>
</label>
<form>
Have you submitted this form before?
<input type="checkbox" name="hasBeenSubmitted" value="1" onclick="checkDisabled(this)">
<br>
Foo: <input type="text" name="foo">
<br>
Bar: <input type="text" name="bar">
<br>
<input type="submit">
</form>

Frustratingly simple Javascript Help Required

I am making a form field where I would like to do a simple show-hide to display div's on a radio button.
<form id="basic" name="basic">
<label><input name="formelement" type="radio" value="yes" /> Yes </label>
<label><input name="formelement" type="radio" value="no" /> No </label>
<div id="yes" style="display: none;">
This is the div that displays that shows when 'Yes' is selected.
</div>
<div id="no" style="display: none;">
This is the div that displays that shows when 'No' is selected.
</div>
</form>
I have played with some various javascript's I have found online and have achieved not a lot of success as most of them online manage to show-hide one div. Getting the 'yes' to hide when 'no' is selected and vice-versa is the tricky part. If anyone could provide some assistance that would be really appreciated!
Just paste these code between head tags
<script type="text/javascript">
window.onload=function(){
var el1 = document.getElementsByName('formelement')[0];
var el2 = document.getElementsByName('formelement')[1];
el1.onchange=function(){
var show=el1.value;
var hide=el2.value;
document.getElementById(show).style.display='block';
document.getElementById(hide).style.display='none';
}
el2.onchange=function(){
var show=el2.value;
var hide=el1.value;
document.getElementById(show).style.display='block';
document.getElementById(hide).style.display='none';
}
}
</script>
DEMO.
The below is assuming value of radio is same as id of the div..
function getRadioVal(name){
var oRadio = document.forms[0].elements[name];
for(var i = 0; i < oRadio.length; i++)
if(oRadio[i].checked)
return oRadio[i].value;
return '';
}
//hide both divs..
document.getElementById("yes").style.display = "none";
document.getElementById("no").style.display = "none";
//show only one of them..
document.getElementById(getRadioVal("formelement")) = "block";
Dealing with javascript without any libraries is a pain when things get complex, I would recommend libraries such as jQuery
this is what you want
How can I check whether a radio button is selected with JavaScript?
assign onclick event and you are good to go.

If radio button checked add new form element using dom?

How do I use DOM in Javascript to check if a radio button is checked and then if so add new form elements to datesettings?
//Radio buttons
<input type="radio" id="dateoption" name="dateoption" value="1">
<input type="radio" id="dateoption" name="dateoption" value="2">
//Add new form elements
<span id="datesettings"></span>
Im currently reading a Javascript book but its not helping me understand. If someone could help me with this example then maybe the penny will drop. Thanks for your time.
Check out this page:
It explains the process so you understand why you're doing it a certain way, AND it gives good example code.
http://www.webdevelopersnotes.com/tips/html/finding_the_value_of_a_radio_button.php3
You would write a function to do the check, like this:
function CheckDateOptions() {
var o1 = document.getElementById("dateoption1");
var o2 = document.getElementById("dateoption2");
var eSettings = document.getElementById("datesettings");
if(o1.checked) {
eSettings.appendChild(...);
}
else if(o2.checked) {
eSettings.appendChild(...);
}
}
But, you have to make sure to assign your radio buttons unique id values. You can duplicate names to group the radio buttons, but for any element, the id should be unique.
<form id="TestForm">
<!-- //Radio buttons -->
<input type="radio" id="dateoption1" name="dateoption" value="1">Text 1</input>
<input type="radio" id="dateoption2" name="dateoption" value="2">Text 2</text>
<!-- //Add new form elements -->
<span id="datesettings"></span>
</form>

how to change color of text following function in javascript

Ok before i make spaghetti of this code i thought id ask around here. ive made a quiz for an online site.
The answers are stored in an array, and ive a function that checks the answers array to what youve clicked. then it counts them and gives you your score.
but i want to change the clor of the right answer wen the user clicks the score button. so the correct answers are highlighted. something like this https://www.shutterpoint.com/Home-Quiz.cfm (just hit submit at the bottom, no need to do the quiz).
the little answer icon at the side looks flashy but id rather just have the text change color. heres how my questions are formatted
<p>Film speed refers to:</p>
<p id = "question1">
<input type="radio" name="question1" id="Wrong" value = "a" onClick = "recordAnswer(1,this.value)"/>How long it takes to develop film. <br/>
<input type="radio" name="question1" id="Wrong" value = "b" onClick = "recordAnswer(1,this.value)"/>How fast film moves through film-transport system. <br/>
<input type="radio" name="question1" id="Answer" value = "c" onClick = "recordAnswer(1,this.value)"/> How sensitive the film is to light. <br/>
<input type="radio" name="question1" id="Wrong" value = "d" onClick = "recordAnswer(1,this.value)"/> None of these makes sense. <br/></p>
and these are the two functions that are called throughout. record answer is called every time the user clicks a button
function recordAnswer(question,answer)
{
answers[question-1] = answer;
}
this is the final button which calculates the score
function scoreQuiz()
{
var totalCorrect = 0;
for(var count = 0; count<correctAnswers.length;count++)
{
if(answers[count]== correctAnswers[count])
totalCorrect++;
}
<!--
alert("You scored " + totalCorrect + " out of 12 correct!");
-->
}
another function is best i think. ive already made attempts at it and know i have to set the color using
document.getElementById('Answer').style.color = '#0000ff';
onyl problem is 'Answer' doesnt seem to be registering. anyone shed some light?
ok so i cant have two or more of the same ids.
what about
if(value == correctAnswers[])
{
// change the color.
}
QUICK RESPONCE:
USE <P>
<p>
<input type="radio" name="question_1" class="wrong" value="a" />
How long it takes to develop film.
</p>
THEN
if(value == correctAnswers[])
{
YOUR_ELEMENT.parentNode.style.color = 'green';
}
IMPROVEMENT
DEMO: http://jsbin.com/aceze/26
hi Overtone!
first of all you need to restyle a litte your HTML schema!
you have multiple id="Wrong" instead of class="Wrong"
then here how your code should look:
var answers = { 1:'a' , 2:'f' , 3:'h' };
function checkQuestions() {
var form_elements = document.question_form.elements.length;
for ( var i = 0; i < form_elements; i++ )
{
var type = question_form.elements[i].type;
if ( type == "radio" ){
var quest = question_form.elements[i];
//if ( quest.checked ) {
var question_index = parseInt(quest.name.split('_')[1]);
//}
if ( quest.value == answers[question_index] ) {
quest.parentNode.style.border = '1px solid green';
quest.parentNode.style.color = 'green';
} else {
//quest.parentNode.style.border = '1px solid red';
quest.parentNode.style.color = 'red';
}
}
}
}
USE a FORM and one time SUBMIT BUTTON instead of adding onclick to each RADIO like this
<form name="question_form" id="question_form" method="POST" action='#'>
<div id="question_1"> <H4>QUESTIONS TIME 1</H4>
</div>
<p>
<input type="radio" name="question_1" class="wrong" value="a" />
How long it takes to develop film.
</p>
<p>
<input type="radio" name="question_1" class="wrong" value="b" />
How fast film moves through film-transport system.
</p>
<p>
<input type="radio" name="question_1" class="answer" value="c" />
How sensitive the film is to light.
</p>
<p>
<input type="radio" name="question_1" class="wrong" value="d" />
None of these makes sense.
</p>
...
...
<input type="radio" name="question_2" class="wrong" value="h" />
<span>None of these makes sense.
</span>
</p>
<input type="submit" name="submit" onclick="checkQuestions();return false;" value="submit"/>
</form>
PS: demo example updated with style... for sake!
You should format your ids in a more usable way.. I'd suggest something similar to questionNUMBER_answerVALUE.
Then it'd be a simple matter of...
for (var i=0; i<correctAnswers;i++) {
document.getElementById("question" + (i+1) + "_answer" + correctAnswers[i].toUpperCase()).style.color = "#0000FF";
};
Just check I've got your zero/non-zero indexing correct with regard to question/ answer numbers.
Instead of using a <p> I would consider using a <label for='question1_answerA'>How long it takes to develop film.</label>. You can still use a jQuery selector to find it and it feels more semantically correct. You will then also be able to select the option by clicking the text.
Although your other HTML isn't semantically correct. You need to give each radio a unique ID.
Obligatory jquery solution:
var highlightCorrect = function(){
$(".Answer").css("color", "#00FF00");
}
This is all assuming that you fix your HTML to use classes rather than IDs for "Wrong" and "Answer".

Categories

Resources