So I am trying to create a page where one can change the background with colorPicker. And it does work, only if I change it, I cannot change it again without refreshing the page. For instance, I changed the BGCR to red, but to change it to Yellow I have to refresh the page. SO what can I do to make it work? here is the code:
const color = document.getElementById('colorPick').value
document.getElementById('changeColor').onclick = changeCol
function changeCol() {
document.body.style.backgroundColor = color
}
<input id="changeColor" type="button" value="Change the Color">
<input type="color" id="colorPick">
When you write:
const color = document.getElementById('colorPick').value;
you're immediately picking up the color value rather than caching the element which means you can't use it again.
Instead do:
const color = document.getElementById('colorPick');
and in your function just assign color.value to the background.
const color = document.getElementById('colorPick');
document.getElementById('changeColor').onclick = changeCol;
function changeCol() {
document.body.style.backgroundColor = color.value;
}
<input id="changeColor" type="button" value="Change the Color">
<input type="color" id="colorPick">
As a second solution, if you want you could remove the button which is not required to change the color.
const color = document.getElementById('colorPick');
function changeCol() {
document.body.style.backgroundColor = color.value;
}
<input type="color" id="colorPick" onchange="changeCol()">
Related
I have a form with several fields that are required, and many that are not required. I want the required fields to be pale pink until they are clicked on and then revert to the default color of all of the fields. I haven't really tried anything because I am not sure how to formulate it. I created a different class for the fields with rgba color value. One example I found does addClass, but the fields I need to change already have a class to define their width, outline, etc. Would addClass CHANGE an existing class, OR is there a "changeClass" functionality or something like that? I tried to modify the answer here: Change Class value With Javascript to work when I clicked the field but that did not work. I tried using document.querySelectorAll too because I have multiple fields separated by other non-required fields and I do not want them to all have the same id or be in the same divs.
I tried
function changeClass(){
document.getElementByClass(".reqd").className = "ssmall4";
}
or
function changeClass(){
document.querySelectorAll(".reqd").className = "ssmall4";
}
with
<input onClick="changeClass()" type="number" id="certYear" name="certYear"value="2020" class ="reqd">
Can anyone connect the dots for me?
I can now get it to work on one field by using:
`<label for="certYear">Certification Year:
<br>
</label>
<input type="number" id="certYear" name="certYear"value="2020"
onclick="myFunction()" class="reqd">`
and
`function myFunction() {
document.getElementById('certYear').style.backgroundColor = "white";
}`
But if I change the function to document.getElementsByClassName I get
"Uncaught TypeError: Cannot set property 'backgroundColor' of undefined"
Same if I try to use document.querySelectorAll (I assume in this one it's because I have to define a variable and I do not know how to enact the bg style color change any way other than above)
I suppose I could just copy the function like 10 times, once for each field and just rename the function and change the id but this seems rather inelegant.
You can do what you're looking for with pure CSS:
.reqd {
background: pink;
}
.reqd:active {
background: white;
}
Substitute in your proper colours, and if you need you can target just the background-color, but essentially this should do it if all you're looking for are pink text fields that are white when they are clicked on ("active").
Actually you can do it without classes.
Do you mean something like this?
const reqInp = document.querySelectorAll('input[required]'); // same as css selector
const allInp = document.querySelectorAll('input[type="text"]'); // all inputs
for (var i=0; i < reqInp.length; i++) { // iterate the required ones
reqInp[i].addEventListener('focus', function() { // if one of them has focus on it
allInp.forEach(function(element){ element.style.background = 'pink'; }) // color all input to pink (or whatever you want)
this.style.background = 'white'; // except this
});
// edit:
reqInp[i].addEventListener('blur', function() { // if one of them loose focus
allInp.forEach(function(element){ element.removeAttribute('style'); }) // remove style attribute so it will return to intial state
});
}
input {display: block; width: 100%;}
input[required] {background: pink;}https://stackoverflow.com/questions/59831874/simple-js-to-change-field-color-when-changed/59832111#
<input type="text" />
<input type="text" />
<input type="text" placeholder="required" required />
<input type="text" placeholder="required" required />
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" placeholder="required" required />
<input type="text" placeholder="required" required />
<input type="text" />
<input type="text" />
<input type="text" />
I have a form with input elements:
<form method="POST" action="User.do">
<div id="buddy-form-group">
<input type="text"
class="form-control form-input-field form-interests-input-field"
name="interests"
onchange="checkFilled()">
</div>
<br/><br/><button class="btn btn-success" type="submit">Send</button>
</form>
I have a scrip that takes all elements of class form-interests-input-field and checks if they are empty. If empty, it sets the color to red, else to green:
function checkFilled() {
var interests = document.getElementsByClassName("form-interests-input-field");
for (var i = 0; i<interests.length; i++) {
if (interests[i].value = "") {
interests[i].style.backgroundColor = "red";
}
else {
interests[i].style.backgroundColor = "green";
}
}
}
The problem is, the color of all fields gets changed to green if at least one field gets field. Once they are green, it never changes to red, even if I erase all the input. I suspect the script puts the green color property on class, rather than individual element. What is the best way to fix it?
Wanted to do this by using css. This worked for me.
input:not([value = ""]){
background-color: black;
color: white;
}
Something like the following should work:
<script>
function checkFilled() {
var interests = document.getElementsByClassName("form-interests-input-field");
for (var i = 0; i<interests.length; i++) {
if (interests[i].value == '') {
interests[i].style.backgroundColor = 'red';
} else {
interests[i].style.backgroundColor = 'green';
}
}
}
</script>
<form>
<div id="buddy-form-group">
<input type="text"
class="form-control form-input-field form-interests-input-field"
name="interests"
onkeyup="checkFilled()">
</div>
<br/><br/>
<button class="btn btn-success" onclick="checkFilled()" type="button">Send</button>
</form>
Changed the = to == in the if statement.
With the addition of the onkeyup and onclick fields, it does what you want. When you click the button, it checks the value of the input field and sets the background color accordingly. It also sets the input field's background color as you type.
So I am working on a project involving input type color. I need to make a gradient using these, how would I do this?
Here is color tags
<div id="part1" align=center>
<input type="color" id = color>
<input type="color" id = color2>
EDIT:
ive only tried tried
$("body").css("background-color",clr);
but that cant do gradients as far as I am aware
As your code provided is not completed:
What does the variable clr mean?
When will the input value take effects on the background?
Here I would provide a sample code that I try to guess what you want to do as
I mean I want to change background: linear-gradient(red,blue) so that I can use input type="color" to change the color of the gradient
Here is the sample code to use a button to assign the background with gradient color.
Hope this can help you.
$("#btn_color").on('click', function(){
var color = $("#color").val();
var color2 = $("#color2").val();
var str = "linear-gradient(" + color + "," + color2 + ")";
$("body").css("background",str);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<div id="part1" align=center>
<input type="color" id ='color'>
<input type="color" id ='color2'>
</div>
<button id="btn_color">Click me </button>
</body>
</html>
you need to put the value of the gradient desired in the background property
Check this url for more information https://www.w3schools.com/css/css3_gradients.asp
Here I put a working example:
function changeBackground(){
const color1 = document.getElementById("color").value;
const color2 = document.getElementById("color2").value;
document.body.style.background = `linear-gradient(${color1}, ${color2})`;
}
html, body{
height: 100%;
}
<div id="part1" align="center">
<input type="color" id ="color">
<input type="color" id ="color2">
<button onClick="changeBackground()">Change background!</button>
</div>
I have two radio buttons, one for the colour red and one for the colour blue. The user selects one and the selected colour appears as the background colour. That's what I want, and I've managed to get this to work when it comes to changing an image but for some reason my code doesn't work.
When I select red, nothing happens, then I select blue and the page turns red. I must be doing something really stupid wrong.
JS:
function getColour() {
var rad = document.forms["Form2"]["ColourRad"];
var i, x;
for (i = 0; i < rad.length; i++) {
if (rad[i].checked) {
x = rad[i].value
}
}
changeColour(x);
}
function changeColour(colour) {
if (colour == "Blue") {
document.body.style.backround = "Blue"
} else if (colour == "Red") {
document.body.style.background = "Red"
}
}
HTML:
<body>
<form name="Form2">Do you prefer the colour red or blue?
<input type="radio" name="ColourRad" onchange="getColour()" value="Blue" />Red
<input type="radio" name="ColourRad" onchange="getColour()" value="Red" />Blue
</form>
</body>
JSfiddle: http://jsfiddle.net/rwowf5j8/29/
Using your function to change the background color:
function getColour() {
var rad = document.forms["Form2"]["ColourRad"];
var i, x;
for (i = 0; i < rad.length; i++) {
if (rad[i].checked) {
x = rad[i].value
}
}
changeColour(x);
}
function changeColour(colour) {
//if the value of the input is the color, you don't need
//to check if the color is blue or red to set it
document.body.style.background = colour
}
<form name="Form2">Do you prefer the colour red or blue?
<!--in your code, the Red input is with Blue color -->
<input type="radio" name="ColourRad" onchange="getColour()" value="Red" />Red
<!--the same with the Blue input, where the Blue is Red -->
<input type="radio" name="ColourRad" onchange="getColour()" value="Blue" />Blue
</form>
Also you can use this instead:
<form name="Form2">Do you prefer the colour red or blue?
<input type="radio" name="ColourRad" onchange="document.body.style.backgroundColor = this.value" value="red" />Red
<input type="radio" name="ColourRad" onchange="document.body.style.backgroundColor=this.value" value="blue" />Blue
</form>
I have fixed your script on http://jsfiddle.net/rwowf5j8/41/
Fixed and tested -- Issue was in the spelling in document.body.style.backround and there were some other tricks to do that easily so I fixed that..
<script>
function getColour(value) {
changeColour(value);
}
function changeColour(colour) {
if (colour == "Blue") {
document.body.style.background = "blue";
}
else if (colour == "Red") {
document.body.style.background = "Red";
}
}
</script>
<body>
<form name="Form2">Do you prefer the colour red or blue?
<input type="radio" name="ColourRad" onchange="getColour('Red')" value="Blue" />Red
<input type="radio" name="ColourRad" onchange="getColour('Blue')" value="Red" />Blue
</form>
</body>
A Very Simple Method to do this..
Hope this helps you.
document.onreadystatechange = function()
{
if(document.readyState == "complete")
{
var blue = document.getElementById("blue");
var red = document.getElementById("red") ;
blue.onclick = function()
{
document.body.style.background = "blue";
}
red.onclick = function()
{
document.body.style.background = "red";
}
}
}
<body>
<form name="Form2">Do you prefer the colour red or blue?
<input id="red" type="radio" name="color" value="Blue" />Red
<input id="blue" type="radio" name="" value="Red" />Blue
</form>
</body>
Here's another method. First, I wait for the document to finish loading. Next, I get a list of all elements that have the name 'colorRad' - this allows me to collect a list of all the radio buttons involved in setting the background color.
Next, I attach an event listener that simply gets the value of the radio-button when its selected and finally, applies this to the background-color of the document body's inline style.
Adding a new colour option is as simple as duplicating one of the radio buttons and changing the text displayed in it's label and by setting it's value - this label also allows you to select a radio button with the text, as opposed to limiting the target area to the size of the radio-button's circle only.
Lastly, since the onRadBtnChanged function is attached to each radio-button's object, when the function is called, the this parameter refers to the radio-button object itself. This allows us to get info from the radio-button's value, and avoids having to handle each option specifically, as you have done in your changeColor function. Also, we save the wasted cpu cycles of iterating through the entire list each time, as you do in getColor - only one can be selected at a time - attaching the event-handler to the object itself means that we only need concern ourselves with the particular element that changed. (the change event only fires when the radio-button is selected. It does not fire when the selection of a different one causes one to be deselected - it only fires on selection, or 'checking')
Example:
<!doctype html>
<html>
<head>
<script>
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
var colRadBtns = document.getElementsByName('colorRad');
var i, n = colRadBtns.length;
for (i=0; i<n; i++)
{
colRadBtns[i].addEventListener('change', onRadBtnChanged, false);
}
}
function onRadBtnChanged(evt)
{
document.body.style.backgroundColor = this.value;
}
</script>
</head>
<body>
<label><input name='colorRad' value='red' type='radio'/>Red</label>
<label><input name='colorRad' value='blue' type='radio'/>Blue</label>
<label><input name='colorRad' value='yellow' type='radio'/>Yellow</label>
<label><input name='colorRad' value='green' type='radio'/>Green</label>
<label><input name='colorRad' value='orange' type='radio'/>Orange</label>
</body>
</html>
The 2 things you needed to do were:
Switch the values in the input tags because they didn't match up.
In the changeColour() function, you didn't fully spell out background in document.body.style.backround you missed the g.
I also switched the script tags from the top to be at the bottom, right before the closing body tag just because I usually do it like that.
Fixing those two small issues makes it run perfectly.
Use this instead:
document.body.style.backgroundColor
basically the style property was wrong, it should be backgroundColor
but you can get the same effect much simpler, for example:
onchange="document.body.style.backgroundColor=this.value;"
I am unable to get the function AreaT() to verify and validate the entered value in the input box as the answer to the area of a triangle.
I keep getting "wrong" message even for the correct answer.
What am I doing wrong?
Thank you for taking the time to check my code.
<html>
<head>
<script>
var height = Math.floor(Math.random()*20 +1);
var base = Math.floor(Math.random()*30 +2);
var area = getElementById("area");
function AreaT(){
document.getElementById('height').value = height;
document.getElementById('base').value = base;
if(area== 1/2 * base * height){
document.write("correct")
}
else{
document.write("wrong");
}
}
</script>
</head>
<body>
<form>
<h2>HEIGHT:</h2><input type="button" size="20" id="height"/>
<h2>BASE: </h2><input type="button" size="20" id="base"/>
<h2>AREA: </h2>Enter The Area here:<input type="text" size="20" id="area"/>
<input type="button" size="20" value = "Calculate" onClick ="AreaT()"/>
</form>
</body>
</html>
Try this:
HTML
<body>
<h2>HEIGHT:</h2><input type="button" size="20" id="height"/>
<h2>BASE: </h2><input type="button" size="20" id="base"/>
<h2>AREA: </h2>Enter The Area here:<input type="number" size="20" id="area"/>
<input type="button" size="20" value = "Calculate" onClick ="AreaT()"/>
</body>
Javascript (put in <header> tag)
var height = Math.floor(Math.random()*20 +1);
var base = Math.floor(Math.random()*30 +2);
document.getElementById('height').value = height;
document.getElementById('base').value = base;
function AreaT(){
var area = document.getElementById("area").value;
if(area == 1/2 * base * height){
document.write("correct")
}
else{
document.write("wrong");
}
}
Adding on to what was already mentioned, you need to add a .value to the area element as well. I also changed the input type of AREA to number.
Change getElementById("area") to document.getElementById("area").value. You also need to assign area from inside your AreaT() function, otherwise it's not gonna get the value that the user typed in.
Also, your javascript needs to be below those form elements, otherwise it can't "see" them and you will get undefined values.