Change a class with a selector using javascript - javascript

I'm new to web programming, and I have been trying to do a true/false test, and when the answers are submitted, the answers change colors depending if it's correct or not.
At first, I used labels for each input:
<h3>1. Father Christmas and Santa Claus are the same man</h3>
<input type="radio" id="1bon" name="q1" value="Non" >
<label for="1bon" > True </label> <!-- label is for css -->
<input type="radio" id="1non" name="q1" value="Bon">
<label for="1non" > False </label><br/>
And in the css, I used " input[value=Bon] + label" or "input[value=Non] +label" with a "background color : blue ", and in a JS, I used label[i].style.background to change the color. It's does change the color, but only of the radio button, and when not checked, which is exactly what I'm trying to do. It comes from the fact I don't know how to select the label of a precise input[x=y]:selector.
So I rewrote the whole thing without any labels
<h3>1. Father Christmas and Santa Claus are the same man </h3>
<input type="radio" class="input" id="1bon" name="q1" value="Non"> True
<input type="radio" class="input" id="1non" name="q1" value="Bon"> False
With new css:
.input {
background-color: #fff;
display:inline-block;
width:5%;
padding:10px;
border:1px solid #ddd;
margin-bottom:10px;
cursor:pointer; /* new selectoon type */
}
.input:checked{
background-color: #4876ff;
}
So, when just checked, it is blue, but when the answers are submitted, depending of the value of the input, it change the color of the class:checked.
It there any way do modify the style of a class with a selector in javascript ?
Also, if the user decides to change his answer for a question, the checked have to go back to being color neutral.
Thank you for your help.

You can use this function to change class of element as you explained earlier. But changing color of checkbox is not possible without using third party plugin or customized elements. Please check this link
function Test2($this){
var radios = document.getElementsByName('q1');
for(i=0; i< radios.length; i++){
var element = radios[i];
element.classList.remove("correctAnswer");
element.classList.remove("wrongAnswer");
}
if($this.value === "Non"){//Assume "Non" is correct answer
$this.classList.add("correctAnswer");
}else{
$this.classList.add("wrongAnswer");
}
}

Related

How do I validate a radio button with JavaScript?

How do I validate a radio button? I want to make it so that if the user left the radio button unclicked the section background will turn a red colour/color.
Here is the HTML Page
<p id="caption_project">Project Selection
<br/>
<input type="radio" name="f__project" id="in_restaurant" value="restaurant"/>
<label for="in_restaurant">LEGO Project</label>
<br/>
<input type="radio" name="f__project" id="in_humber" value="Humber News"/>
<label for="in_humber">Humber Current Project</label>
<br/>
<input type="radio" name="f__project" id="in_self" value="self-determined"/>
<label for="in_self">Self-determined Project</label>
</p>
So how do I turn the background red when they leave it unchecked?
You need to think of some event the user will fire which you want to trigger the function that makes the background go red. That could be if the user clicks on the next form control. Then when that event fires you test whether they checked any radio buttons. If they did not (!checked) then you set the style attribute of your p element to background:red:
const nextThing = document.querySelector('#next-thing');
const p = document.querySelector('p');
nextThing.addEventListener('click', function(){
const checked = document.querySelector("input[name='f__project']:checked");
if(!checked){
p.setAttribute('style', 'background:red');
}
});
<p id="caption_project">Project Selection
<br/>
<input type="radio" name="f__project" id="in_restaurant" value="restaurant"/>
<label for="in_restaurant">LEGO Project</label>
<br/>
<input type="radio" name="f__project" id="in_humber" value="Humber News"/>
<label for="in_humber">Humber Current Project</label>
<br/>
<input type="radio" name="f__project" id="in_self" value="self-determined"/>
<label for="in_self">Self-determined Project</label>
</p>
<button id='next-thing'>Next form control</button>
Use document.querySelector("input[name='f__project']:checked"). If this returns null, none of the radio buttons were checked, and you can display the red background.
If this is in a <form> you can add the required attribute to the radio buttons. If they try to submit the form without selecting one of them, the browser will display a validation error.
Use document.getElementById('id').checkedthe statement returns True or False.
const checkedRadioButton = document.
querySelector("input[name='f__project']:checked");
if (!checkedRadioButton) {
// No values are selected
} else {
// Some value is selected and the element is stored in checkedRadioButton
}
You can use CSS to manipulate the colour depending on whether the radio input is checked or not.
input[type="radio"] {
display: none;
}
input[type="radio"] + label {
border: 5px solid lightblue;
background-color: lightblue;
cursor: pointer;
display: block;
height: 40px;
width: 200px;
text-align: center;
line-height: 40px;
}
input[type="radio"]:checked + label {
border: 5px solid blue;
background-color: dodgerblue;
}
Or else you can make a Javascript function to check
function checkRadioValidity() {
if(document.getElementById('in_restaurant').checked) {
//change CSS here for the element
}
}
The idea of radio button is that it can not be unchecked.
EDIT:
document.querySelector("input[name='f__project']:checked")
will return element if it is checked

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!

Calorie Calculator Javascript Form

I am attempting to make my first attempt at Javascript taking user input and then changing the html of an element to spit out a value. It's a calorie calculator. Here's my HTML, my javascript, and an explanation of what I think is SUPPOSED to happen with my limited knowledge:
<center>
<p>Fill out the form below.</p>
<input type="radio" name="female" value="665.09" oninput="calsPerDay" ><p>Female</p>
<input type="radio" name="male" value="66.47" oninput="calsPerDay" ><p>Male</p>
<input id="age" type="number" oninput="calsPerDay"><p>Age</p><br>
<input id="height" type="number" oninput="calsPerDay"><p> Height- In Inches (12 inches=1 foot)</p>
<input id="weight" type="number" oninput="calsPerDay"><p> Weight (in pounds)</p><br>
</center>
<p id="totalCals"> </p> <p>kcal per day</p>
function calsPerDay() {
var age=document.getElementById("age").value;
var height=document.getElementById("height").value;
var weight=document.getElementById("weight").value;
var female=document.getElementsByName("female").value;
var male=document.getElementsByName("male").value;
if (document.getElementsByName("male").checked) {
var maleCals = male+ (13.75 * weight/2.2) + (5.0 * (height * 2.54) - (6.75 x age);
document.getElementById("totalCals").innerHTML = maleCals;
} else (document.getElementsByName("female").checked) {
var femaleCals = female + (9.56 * weight/2.2) + (1.84 * (height * 2.54) - (4.67 x age);
document.getElementById("totalCals").innerHTML = femaleCals;
}
}
What I expect to happen is that the function will first check if the user has checked off male or female. Then if they check off male, it creates a new variable (not sure if this would be the most optimal way to do this anyway0 where it adds male (because I put var male = document.getElementsByName("male").value and its a radio type input, I read that it would read what you put as the value so I assumed that "male" in the variable maleCals would become that value, 66.47. Then I assumed the height and weight would be read as whatever the number the user puts in the input forms and then be spit out as a paragraph for the <p> element with the id of totalCals.
Here's a JS fiddle for it: https://jsfiddle.net/oafu54x3/
My dilemma is that it simply isn't working, when you put in values, nothing's being written in the <p> tags.
Any suggestions would be helpful.
The problem is when you use getElementsByName, it returns an object array not the object you are looking for.
You should use getElementById for those too.
There are numerous problems.
Lets's start by cleaning up the HTML:-
<h1>Fill out the form below.</h1>
<label>Female:
<input id="female" type="radio" name="gender" onchange="calsPerDay()">
</label>
<label>Male:
<input id="male" type="radio" name="gender" onchange="calsPerDay()" checked>
</label>
<label>Age:
<input id="age" type="number" oninput="calsPerDay()" value="50">
years
</label>
<label>Height:
<input id="height" type="number" oninput="calsPerDay()" value="70">
in inches (12 inches=1 foot)
</label>
<label>Weight:
<input id="weight" type="number" oninput="calsPerDay()" value="225">
in pounds
</label>
<label>
Base metabolic rate: <span id="totalCals"></span> kcal per day
</label>
By placing the input elements inside label tags, the user can now click anywhere in the label to give the contained input element focus.
Note also that both the radio buttons need to have the same name attribute. So in order to differentiate between them, they need to have different id attributes.
On some browsers you need to place () at the end of each event handler name. If you can't predict which browser will be used by the client, then it is better to play it safe. So always include them.
To make testing easier, I have added a selected attribute to the male radio button, and default value attributes to the other input elements. Please feel free to remove them before deployment.
The value attributes on the radio buttons are really things that belong in the model (i.e. javascript) not in the view (i.e. html).
Now add a bit of style in CSS:-
label {
display: block;
box-shadow: 0.1em 0.1em 0.2em #888;
margin: 1em;
border-radius: 1ex;
padding: 1ex 1em;
}
input[type=number] {
text-align: right;
border: none;
}
input {
float: right;
}
span {
font-weight: bold;
}
And finally clean up the Javascript:-
function calsPerDay() {
function find(id) { return document.getElementById(id) }
var age = find("age").value
var height = find("height").value * 2.54
var weight = find("weight").value / 2.2
var result = 0
if (find("male").checked)
result = 66.47 + (13.75 * weight) + (5.0 * height - (6.75 * age))
else if (find("female").checked)
result = 665.09 + (9.56 * weight) + (1.84 * height - (4.67 * age))
find("totalCals").innerHTML = Math.round( result )
}
calsPerDay()
I know many people won't agree but I personally find code duplication distracting. In your code document.getElementById(id) is repeated often. So I have extracted that behaviour out into a little helper function find. Now the rest of the code reads so much better.
Because you apply the same scaling factor to weight, height regardless of the gender, I moved that scaling out, and now it is no longer duplicated.
Notice that I assumed the missing closing braces should go at the end of the formulae. I can't check this as I don't have access to the source document where you discovered these formulae.
You also used "x" inside a formula instead of "*". This is a common mistake as one transitions from written algebra to computer algorithms. Take care on this one.
Lastly I have removed all those unnecessary (and distracting) semicolons. In Javascript there are only a few rare occasions where you actually must use semicolons.
You can see a working CodePen here

how to change text between input tags and align label checbox and icon on one line

I currently have this:
<script type="text/javascript">
$(document).ready(function(){
/* als je selectbox gebruikt doe dan deze:
$("#deliveryType").change(function(){
$("img[name=deliveryIcon]").attr("src","images/rushdeliveryicon.png");
});
*/
$('#deliveryType').click(function() {
$deliveryType = document.getElementById("deliveryType");
if ($(this).is(':checked') == true) {
$deliveryType.value="spoed";
$('#deliveryType').text("Spoedlevering");
$("img[name=deliveryIcon]").attr("src","images/rushdeliveryicon.png");
}else{
$deliveryType.value="week";
$('#deliveryType').text("Weeklevering");
$("img[name=deliveryIcon]").attr("src","images/weekdeliveryicon.png");
}
});
});
</script>
<label id="deliverylabel" for="delivery">Leveringsoort
<!-- <select name="deliveryType" id="deliveryType" >
<option value="week">Weeklevering</option>
<option value="rush">Spoedlevering</option>
</select>
-->
<input name="deliveryType" id="deliveryType" type="checkbox" value="week" >Weeklevering</input>
<img name="deliveryIcon" src="images/weekdeliveryicon.png" style="width:64px;height:64px;" /></label>
If i click the checkbox then the text between the input tags need to change:
<input name="deliveryType" id="deliveryType" type="checkbox" value="week">Weeklevering</input>
Next to this i also try to get the text of the label and the checkbox + text + icon aligned on 1 line so that it fits like the rest of the input fields on the form. Please have a look:
http://jsfiddle.net/nqm4bpnu/
problem with CSS is that the checkbox input also takes this style:
div.wrapperDiv
{
width:100%;
float:left;
margin-bottom:20px;
}
but it because it is a checkbox it doesnt need to have such a big width.
any ideas
thank you
First thing is <input> doesn't have a closing tag (</input>) so I have changed it to </input>, added a <span> with different id to display the text and changed click to change (this doesn't matter but I prefer change event for check box)
HTML
<label id="deliverylabel" for="delivery">Leveringsoort</label>
<input name="deliveryType" id="deliveryType" type="checkbox" value="week" />
<span id="displayTypeText">Weeklevering</span> <!-- <-----here -->
<img name="deliveryIcon" src="images/weekdeliveryicon.png" style="width:64px;height:64px;" />
JS
$('#deliveryType').change(function () {
if (this.checked) {
this.value = "spoed";
$('#displayTypeText').text("Spoedlevering");
$("img[name=deliveryIcon]").attr("src", "images/rushdeliveryicon.png");
} else {
this.value = "week";
$('#displayTypeText').text("Weeklevering");
$("img[name=deliveryIcon]").attr("src", "images/weekdeliveryicon.png");
}
});
I am not much of a designer but I think you should add a div with float:left around this . Anyways here is a working fiddle,
fiddle
UPDATED
As I have already mentioned I am not a designer but this should get you going (Add it at the end of the CSS script,
#deliveryType{
width:30%!important;
}
updated fiddle
Try using this --
remove 'Weeklevering' from within your input tag
<input name="deliveryType" id="deliveryType" type="checkbox" value="week" >Weeklevering</input>
and make html like this,
<input name="deliveryType" id="deliveryType" type="checkbox" value="week" >
<span id="label">Weeklevering</span>
change blow line in your jquery code -
$('#deliveryType').text("Spoedlevering");
to this,
$('#label').html("Spoedlevering");
Note: Do this to both the instances in your jQuery code.
To make all three items in single line, add following css -
#deliverylabel { display: block; text-align: left; width: 100% !important; }
#deliverylabel > input { display: inline-block; margin-left: 15px; vertical-align: middle; width: auto; }
hope this helps.

Issue showing div with jquery

I seem to be having a hard time displaying a div when a checkbox is clicked, the issue is pretty straight forward, but i cant seem to find the right jquery solution to resolve this, though i feel like i am very close.
$html=
'<form action="contacted.php" method="POST">
<input type = "hidden" name = "contact" class = "hidden" value = "'.$ip.'">
<input type="checkbox" id="contact'.$ip.'" value = "'.$ip.'" onclick="show()"/>
<div class="hide" style="
display:none;
border:3px
solid black;
background-color:grey;
color:white;
width:200px;
position:absolute;
left:40%;
top:20%;
-moz-border-radius: 15px;
border-radius: 15px;
padding:4px;
z-index:1000;
Width:500px;
">
<textarea name = "notes" style = "" > Let\'s get some notes about that...</textarea>
<input type="submit" value="YES"/>
<input type="button" value="NO" onclick="hide()">
</div>
</form>';
this is in a for loop and $ip is an identifier. but its pretty straight forward.
jquery that i have tried
function show(){
$(this).parent().find('.hide').css("display","block")
}
im trying to display the div hide when the checkbox is clicked (this happens multiple times on the same page) and i cant piece together the right combination from the jquery documentation. Any ideas? im sure this will be simple, I am more than willing to except javascript suggestions :)
add class to input like this and try it please
<input type="checkbox" id="contact'.$ip.'" class="contact_click" value="'.$ip.'" onclick="show()"/>
$('.contact_click').on('click',function(){
$(this).closest('div').css('css','block');
});
Try this
Change
<input type="checkbox" id="contact'.$ip.'" value = "'.$ip.'" onclick="show()"/>
to
<input type="checkbox" id="contact'.$ip.'" value = "'.$ip.'" onclick="show(this)"/>
and script as
function show()
{
this.parent().find('.hide').css("display","block");
}
Pass the clicked element into your function like this
<input type="checkbox" id="contact'.$ip.'" value = "'.$ip.'" onclick="show(this)"/>
and
function show(element){
$(element).parent().find('.hide').css("display","block");
}
you dont even need the class the checkbox is a direct child of the div.
$(this).parent().show(0);
just make sure you bind the click handler to the check box and that will definitely work.
and just to make sure you are binding the event right try this when you click the check box
function test(){
var test = $(this).parent().attr('class');
alert(test);
}
and you should get hide. so if you get hide it is binded correctly

Categories

Resources