How to make function execute after radio option is clicked? JavaScript - javascript

I am wondering how I can make a function execute such as making a text box appear when "Yes" option is clicked. How can I do this as the Yes is part of a radio input type in JS? I prefer an answer in vanilla javascript. It would help a lot! Thank You!
JavaScript
document.querySelector("label[for=ediet]").style.opacity = "100%"; //RIGHT
document.getElementById("edietq").style.opacity = "100%";
}
function init( ) {
var f = document.getElementsByName("form1");
f[0].addEventListener("submit", validateForm);
var yes = document.querySelector("label[for=ediet]");
yes.addEventListener("click", yesClicked);
var showT = document.getElementById("edietq");
showT.addEventListener("click", yesClicked);
}
window.onload = init; ```
**HTML**
<input type="radio" id="yes" name="option">
<label for="yes" id="yesq" value = "option">Yes</label><br><br>
<input type="radio" id="no" name="option">
<label for="No">No</label><br><br>
<label for="ediet">If yes, explain your dietary restrictions</label><br>
<input type="text" id="edietq" name="edietq"><br><br> <!-- Explain Diet-->

You can create a class that the display is none
.hide{
display: none
}
Leave pre added in the input to be hidden
<input type="text" id="edietText" class="hide" name="edietq">
And make a function that removes this class
const yesInput = document.getElementById("yes")
yesInput.addEventListener("click", yesClicked);
function yesClicked(){
let textExp = document.getElementById("edietText");
textExp.classList.remove('hide');
}
And you can do something like this too:
const yesInput = document.getElementById("yes");
const noInput = document.getElementById("no");
const textExp = document.getElementById("edietText");
yesInput.addEventListener("click", yesClicked);
noInput.addEventListener("click", noClicked);
function yesClicked(){
textExp.classList.remove('hide');
}
function noClicked(){
textExp.classList.add('hide');
}
const yesInput = document.getElementById("yes");
const noInput = document.getElementById("no");
const textExp = document.getElementById("edietText");
yesInput.addEventListener("click", yesClicked);
noInput.addEventListener("click", noClicked);
function yesClicked(){
textExp.classList.remove('hide');
}
function noClicked(){
textExp.classList.add('hide');
}
.hide{
display: none
}
<input type="radio" id="yes" name="option">
<label for="yes" id="yesq" value = "option">Yes</label>
<br><br>
<input type="radio" id="no" name="option">
<label for="no">No</label><br><br>
<label for="ediet">If yes, explain your dietary restrictions</label><br>
<input type="text" id="edietText" class="hide" name="edietq">
<br><br> <!-- Explain Diet-->

Use the onclick event listener as shown below:
document.getElementById("dark").addEventListener("click", (e) => {
console.log(e.target.id)
document.body.style.background = "black"
document.body.style.color = "white"
});
document.getElementById("light").addEventListener("click", (e) => {
console.log(e.target.id)
document.body.style.background = "white"
document.body.style.color = "black"
});
<label>Toggle Dark Mode</label>
<input type="radio" name="theme" id="dark" />
<label>Toggle Light Mode</label>
<input type="radio" name="theme" id="light" />
Adjust the code to suit your usecase.

Related

Change the value of a variable depending on a radio button

I have a variable called genderMultiplier which is used in this calculation
const bloodAlcoholContent = (gramsOfAlcohol / ((weight * 1000) * genderMultiplyer))*100;
My genderMultiplier can have 2 values and I have made a radio input for that in HTML
<div class="gender-buttons" id="gender-buttons">
<input class="gender-button" type="radio" name="tools" id="tool-1" value="0.55" checked>
<label class="for-gender-button" for="tool-1">Male</label>
<input class="gender-button" type="radio" name="tools" id="tool-2" value="0.68">
<label class="for-gender-button" for="tool-2">Female</label>
</div>
const genderButtonElement = document.getElementById("gender-buttons")
const genderMultiplyer = parseFloat(genderButtonElement.input);
One radio button is [MALE] and [FEMALE]. So if the user clicks Male then I want the genderMultiplier to be 0.55 and if the user clicks Female then I want the genderMultiplier to be 0.68
Any advice on this?
Change your last line to
const genderMultiplier = parseFloat([...genderButtonElement.children].find(c=>c.checked).value)
To calculate bloodAlcoholContent, you need to know the values gramsOfAlcohol and weight. But you did not show the method for calculating these variables.
const genderButtonElement = document.querySelectorAll('.gender-buttons .gender-button');
genderButtonElement.forEach(function(current, index) {
current.addEventListener('click', function() {
const genderMultiplyer = parseFloat(current.value);
console.log(genderMultiplyer);
});
});
<div class="gender-buttons" id="gender-buttons">
<input class="gender-button" type="radio" name="tools" id="tool-1" value="0.55" checked>
<label class="for-gender-button" for="tool-1">Male</label>
<input class="gender-button" type="radio" name="tools" id="tool-2" value="0.68">
<label class="for-gender-button" for="tool-2">Female</label>
</div>
function getMultiplier()
{
const genderMultiplyer = parseFloat(document.querySelector('input[name="tools"]:checked').value);
alert("The multiplier is: " + genderMultiplyer);
}
<div class="gender-buttons" id="gender-buttons">
<input class="gender-button" type="radio" name="tools" id="tool-1" value="0.55" checked>
<label class="for-gender-button" for="tool-1">Male</label>
<input class="gender-button" type="radio" name="tools" id="tool-2" value="0.68">
<label class="for-gender-button" for="tool-2">Female</label>
</div>
<button onclick="getMultiplier()">Get Multiplier</button>
The pure Javascript way of doing this in your example is as follows:
const genderMultiplyer = parseFloat(document.querySelector('input[name="tools"]:checked').value);
If your are using JQuery you can get it this way:
const genderMultiplyer = parseFloat($('input[name="tools"]:checked').val());

Creating a textarea when user clicks button

I was wondering what the best way to approach this next feature is.
Right now, when user selects "no" an alert appears. However, I would like for a text area box to appear, instead. Any help or leads on how to tackle this? My first thought is that my if statement will have to change, correct? Any leads are appreciated. I provided a snippet for you to view of what I have so far.
let button = document.querySelector("input.button");
button.addEventListener("click", question1);
function question1() {
var selection = document.querySelector("input[name='groupOfDefaultRadios']:checked");
if (selection.value == 'yes') {
alert("Thank you for your kindness");
} else {
alert("We are sorry! Please write to us telling us what was wrong");
}
}
<div class="clienthelp-card">
<form id="myForm">
<h4> Was this helpful?</h4>
<div class="custom-control custom-radio">
<input type="radio" class="custom-control-input" id="defaultGroupExample1" name="groupOfDefaultRadios" value="yes">
<label class="custom-control-label" for="defaultGroupExample1">Yes</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" class="custom-control-input" id="defaultGroupExample2" name="groupOfDefaultRadios" value="no">
<label class="custom-control-label" for="defaultGroupExample2">No</label>
</div>
<input class="button" type="button" name="groupOfDefaultRadios" value="Submit">
</form>
</div>
Here are a few ways you can give a user something to enter text into and then handle it as you see fit.
The first way is to insert a textarea element and add a callback so that when the user selects OK, you can do what you want with the text.
The second way is to use prompt as called called out in other comments
function okButtonCallback(evt) {
const textArea = document.getElementById('textarea1');
alert(`Text Area Text: ${textArea.value}`);
}
const btnTextArea = document.getElementById('textarea');
const btnPrompt = document.getElementById('prompt');
// Use a Text Area to get text and
// add a callback to handle the text
// when the user selects ok
btnTextArea.addEventListener('click', e => {
const container = document.getElementById('myContainer');
const textArea = document.createElement('textarea');
textArea.id = 'textarea1';
const okButton = document.createElement('button');
okButton.innerText = 'OK';
okButton.onclick = okButtonCallback;
container.appendChild(textArea);
container.appendChild(okButton);
});
// Use a prompt to get the text
btnPrompt.addEventListener('click', e => {
const enteredText = prompt('Some sort of message');
alert(`Prompt Text: ${enteredText}`);
});
<button id="textarea">Show Text Area</button>
<button id="prompt">Show Prompt</button>
<div id="myContainer"></div>
The built in alert function cannot be used to get user input.
You can add a hidden div which replaces the alert and where you can also add HTML elements.
Please find slightly modified version of your code to get the idea below:
<div class="clienthelp-card">
<form id="myForm">
<h4> Was this helpful?</h4>
<div class="custom-control custom-radio">
<input type="radio" class="custom-control-input" id="defaultGroupExample1" name="groupOfDefaultRadios" value="yes">
<label class="custom-control-label" for="defaultGroupExample1">Yes</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" class="custom-control-input" id="defaultGroupExample2" name="groupOfDefaultRadios" value="no">
<label class="custom-control-label" for="defaultGroupExample2">No</label>
</div>
<input class="button" type="button" name="groupOfDefaultRadios" value="Submit">
</form>
</div>
<div id="result" style="display:none"></div>
<script>
let button = document.querySelector("input.button");
button.addEventListener("click", question1);
function question1() {
var selection = document.querySelector("input[name='groupOfDefaultRadios']:checked");
var result = document.getElementById("result");
if (selection.value == 'yes') {
result.innerHTML = "Thank you for your kindness";
result.style.display = "block";
} else {
var output = "";
output += "We are sorry! Please write to us telling us what was wrong:<br />";
output += "<textarea style='width: 100px; height 100px;'></textarea><br />";
output += "<button>Submit</button>";
result.innerHTML = output;
result.style.display = "block";
}
}
</script>
I think you can create a <textarea id="whatever_you_want" hidden> and you add in the else document.getElementById("whatever_you_want").removeAttribute("hidden")
You can toggle a hidden text field, based on the selection of the radio button.
In the example below, a class is added to the text field to hide it. When the choice is changed to "yes", the class is added; if it is changed to "no", the class is added back.
let submitButton = document.querySelector('input.button');
let radioButtons = document.querySelectorAll('input[type="radio"]');
let hiddenTextArea = document.querySelector('.custom-textarea textarea');
// Add listeners
Array.from(radioButtons).forEach(radio => {
radio.addEventListener('change', (e) => {
let hiddenWrapper = hiddenTextArea.parentElement;
hiddenWrapper.classList.toggle('hidden-field', e.target.value !== 'no');
});
});
submitButton.addEventListener('click', question1);
function question1() {
var selection = document.querySelector("input[name='groupOfDefaultRadios']:checked");
if (selection.value == 'yes') {
alert("Thank you for your kindness");
} else {
alert("We are sorry! Please write to us telling us what was wrong");
}
}
.hidden-field {
display: none;
}
<div class="clienthelp-card">
<form id="myForm">
<h4> Was this helpful?</h4>
<div class="custom-control custom-radio">
<input type="radio" class="custom-control-input" id="defaultGroupExample1" name="groupOfDefaultRadios" value="yes">
<label class="custom-control-label" for="defaultGroupExample1">Yes</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" class="custom-control-input" id="defaultGroupExample2" name="groupOfDefaultRadios" value="no">
<label class="custom-control-label" for="defaultGroupExample2">No</label>
</div>
<!-- Here -->
<div class="custom-control custom-textarea hidden-field">
<textarea name="feedback"></textarea>
</div>
<input class="button" type="button" name="groupOfDefaultRadios" value="Submit">
</form>
</div>
Another approach is to createElement when the user mark the "NO". I put notes inside this general demo:
let radioI = document.querySelectorAll("input[name='groupOfDefaultRadios']"); // get radio in order to attach eventListener:
radioI.forEach((item) => { item.addEventListener("change", question1)}); // add change event that will trigger this function:
function question1() {
var selection = document.querySelector('input[name="groupOfDefaultRadios"]:checked'); // this is your lines
if (selection.value == 'yes') {
alert('Thank you for your kindness');
// and/or submit the form progrematically using submit() etc... and/or redirect the user etc..
} else {
// create textarea element and display the submit button:
var textA = document.createElement('textarea');
textA.setAttribute('name', 'notHelpNote');
textA.setAttribute('required', 'true');
textA.placeholder = 'We are sorry! Please write to us telling us what was wrong';
document.querySelector('#myForm').appendChild(textA);
document.querySelector('#myForm input[type="submit"]').style.display = 'block';
}
}
<div class="clienthelp-card">
<form id="myForm">
<h4> Was this helpful?</h4>
<div class="custom-control custom-radio">
<input type="radio" class="custom-control-input" id="defaultGroupExample1" name="groupOfDefaultRadios" value="yes">
<label class="custom-control-label" for="defaultGroupExample1">Yes</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" class="custom-control-input" id="defaultGroupExample2" name="groupOfDefaultRadios" value="no">
<label class="custom-control-label" for="defaultGroupExample2">No</label>
</div>
<input class="button" type="submit" name="groupOfDefaultRadios" value="Submit" style="display: none;">
</form>
</div>
I guess you can create a:
<input type="hidden" name="message" id="myAwesomeHiddenMessageField">
in your form and replacing your second alert by a prompt displaying the question like this :
let promptMessage = prompt("We are sorry! Please write to us telling us what was wrong");
And on submit or whatever :
document.querySelector('#myAwesomeHiddenMessageField').val(promptMessage);
Or you could use document.createElement to append a textearea to your form when "no" is selected. But I'm to lazy to help you more with this. And if you wan't to do this you gonna have to hide the generated textarea if the user choose "yes" in the end. Not sure if it's the best UX choose to make.
Cheers.

Display different divs using input checkbox

I want to use 3 input checkbox to display 3 different div. I am using this code but the only one working is "Course 1" and I can't figure out why. I guess it is something pretty easy, but I can't see it:
document.getElementById('checkbox1');
checkbox1.onchange = function() {
if (checkbox1.checked) {
course1.style.display = 'block';
} else {
course1.style.display = 'none';
}
};
document.getElementById('checkbox2');
checkbox2.onchange = function() {
if (checkbox2.checked) {
course2.style.display = 'block';
} else {
course2.style.display = 'none';
}
};
document.getElementById('checkbox3');
checkbox3.onchange = function() {
if (checkbox3.checked) {
course3.style.display = 'block';
} else {
course3.style.display = 'none';
}
};
<form>
<label class="switch">
<input type="checkbox" id="checkbox1" checked="true"> Course 1
</label>
</form>
<form>
<label class="switch">
<input type="checkbox" id="checkbox2" checked="true"> Course 2
</label>
</form>
<form>
<label class="switch">
<input type="checkbox" id="checkbox3" checked="true"> Course 3
</label>
</form>
<br>
<div id="course1"> Text course 1
</div>
<br>
<div id="course2"> Text course 2
</div>
<br>
<div id="course2"> Text course 3
</div>
Example: https://codepen.io/antonioagar1/pen/dqGaoO
You can try this simple code instead of your own code:
document.addEventListener("change", function(ev){
if(ev.target.id.substr(0,8)=="checkbox") document.querySelector("[id='course"+ev.target.getAttribute("id").slice(-1)+"']").style.display=ev.target.checked?"block":"none";
});
you have two div with id course2. first, change it to course3 and then try.
Check result online

Change div color by finding input background-color

How do I change the JavaScript code to find the input label's HTML background-color instead of having to manually insert the color into the JavaScript like in this snippet?
function ChangeColor(color) {
var clrDiv = document.getElementsByClassName("colorDiv")[0];
clrDiv.style.backgroundColor = color;
}
document.getElementById("select1").onclick = function() {
ChangeColor("red");
}
document.getElementById("select2").onclick = function() {
ChangeColor("green");
}
document.getElementById("select3").onclick = function() {
ChangeColor("blue");
}
.colorDiv {
width: 50px;
height: 50px;
}
<section>
<input id="select1" name="test" type="radio" />
<label style="background-color:red;" for="select1">Red</label>
<input id="select2" name="test" type="radio" />
<label style="background-color:green;" for="select2">Green</label>
<input id="select3" name="test" type="radio" />
<label style="background-color:blue;" for="select3">Blue</label>
</section>
<footer>
<div class="colorDiv"></div>
</footer>
Is this what you are looking for? Instead of a color, I pass the id of the select, find the label for the input, and then use that label's background color to set the div background color.
If you are alright using jquery this could be greatly simplified.
function findLableForControl(el) {
var idVal = el.id;
labels = document.getElementsByTagName('label');
for( var i = 0; i < labels.length; i++ ) {
if (labels[i].htmlFor == idVal)
return labels[i];
}
}
function ChangeColor(color) {
var clrDiv = document.getElementsByClassName("colorDiv")[0];
clrDiv.style.backgroundColor = findLableForControl(document.getElementById(color)).style.backgroundColor;;
}
document.getElementById("select1").onclick = function() { ChangeColor("select1"); }
document.getElementById("select2").onclick = function() { ChangeColor("select2"); }
document.getElementById("select3").onclick = function() { ChangeColor("select3"); }
.colorDiv{
width:50px;
height:50px;
}
<section>
<input id="select1" name="test" type="radio" />
<label style="background-color:red;" for="select1">Red</label>
<input id="select2" name="test" type="radio" />
<label style="background-color:green;" for="select2">Green</label>
<input id="select3" name="test" type="radio" />
<label style="background-color:blue;" for="select3">Blue</label>
</section>
<footer>
<div class="colorDiv"></div>
</footer>
You can make your code much simpler by following a few easy steps:
Assign the ChangeColor function directly to the onclick, no need for an intermediary anonymous function and no need to pass anything.
In the ChangeColor function, use this to access the element that raised the event (i.e. the input that you clicked on).
Use the querySelector function to select the associated label by its for attribute.
function ChangeColor() {
var clrDiv = document.getElementsByClassName("colorDiv")[0];
clrDiv.style.backgroundColor = document.querySelector("label[for=" + this.id + "]").style.backgroundColor;
}
document.getElementById("select1").onclick = ChangeColor;
document.getElementById("select2").onclick = ChangeColor;
document.getElementById("select3").onclick = ChangeColor;
.colorDiv {
width: 50px;
height: 50px;
}
<section>
<input id="select1" name="test" type="radio" />
<label style="background-color:red;" for="select1">Red</label>
<input id="select2" name="test" type="radio" />
<label style="background-color:green;" for="select2">Green</label>
<input id="select3" name="test" type="radio" />
<label style="background-color:blue;" for="select3">Blue</label>
</section>
<footer>
<div class="colorDiv"></div>
</footer>

Validating if the radio button group is selected JQUERY

I'm trying to validate the radio button group,. if not check the span will have a text which indicates that the radio button must be selected,. the problem is,. if I place the codes of radion button validation on top, it does not work, but when it is below,. it works.. Kinda weird,. any idea for this one? thanks
$("#mchoice").submit(function () {
var direction = $('#direction').val();
var quiztxtBox = document.getElementsByName('quiztxtBox[]');
var isSubmit;
var names = [];
var err = document.getElementsByName('errMchoice[]');
// For radio button answers.
$('input[type="radio"]').each(function(){
names[$(this).attr('name')] = true;
});
if (!direction)
{
$('#direction').focus();
$('#direction').css({"background-color":"#f6d9d4"});
$('#direction').nextAll('span').html('Type in direction.');
event.preventDefault();
}
else
{
$('#direction').css({"background-color":"#fff"});
$('#direction').nextAll('span').html("");
}
for(correct_answer in names)
{
var radio_buttons = $("input[name='" + correct_answer + "']");
if( radio_buttons.filter(':checked').length == 0)
{
radio_buttons.nextAll('span').html('Select the answer.');
event.preventDefault();
}
else
{
radio_buttons.nextAll('span').html('');
}
}
// Choices fields
$("[name='quiztxtBox[]']").each(function(){
if (!this.value.length)
{
$(this).css({"background-color":"#f6d9d4"}).siblings('span.errorMsg').text('Please type in question/answer!');
event.preventDefault();
}
else
{
$(this).css({"background-color":"#fff"}).siblings('span.errorMsg').text("");
}
});
});
HTML here
<div id="QuestionTBDiv1" >
<label>Question</label><br/>
<input type="text" name="quiztxtBox[]" size="57" id="quiztxtBox[]" placeholder="Question #1"><br/>
<label>Answer</label><br/>
<input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice A"> <input type="radio" class = "choiceA" name="correct_answer1" value="A">
<input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice B"> <input type="radio" class = "choiceB" name="correct_answer1" value="B"><br/>
<input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice C"> <input type="radio" class = "choiceC" name="correct_answer1" value="C">
<input type="text" name="quiztxtBox[]" size="24" id="answer[]" placeholder="Choice D"> <input type="radio" class = "choiceD" name="correct_answer1" value="D"><br>
<span name="errMchoice" class="errorMsg"></span>
</div>
JsFiddle:http://jsfiddle.net/Ej77L/2/
There was a small logical error in your javascript.
Once you set the span with error message of 'Select an answer' you are doing a checking if the question has been filled. If it has been filled then you are making the span text empty.
So instead of that, keep a flag to see if the answer was selected or not. If not selected then set the flag and in later part of the code, don't empty span text
Here's a working DEMO

Categories