button checking a checkbox using javascript - javascript

I am trying to make a button that will toggle between three colors: black, green, and red and will either check a certain box depending on the color. Right now I can make the color toggle but I can't make the check boxes check. I would appreciate the help. I am a beginner (obviously).
Button color green: check box 1
Button color red: check box 2
Button color black: do not check either box 1 or 2
The script looks like:
<script>
var colors = ["green", "red", "black"]
function setColor(el) {
el.colorIdx = el.colorIdx || 0;
el.style.color = colors[el.colorIdx++ % colors.length];
}
</script>
The HTML looks like:
<html>
<button onclick="setColor(this)">This is my Button</button>
<input type="checkbox" name="box1" id="box1" />
<input type="checkbox" name="box2" id="box2" />
</html>
Thanks!

I'd suggest:
var colors = ["green", "red", "black"];
function setColor(el) {
el.colorIdx = el.colorIdx || 0;
el.style.color = colors[el.colorIdx++ % colors.length];
document.getElementById('box1').checked = el.style.color == 'green';
document.getElementById('box2').checked = el.style.color == 'red';
}
JS Fiddle demo.

Do it like this:
var index = el.colorIdx++ % colors.length;
if( index == 2 ) //2 is the index of color black
{
document.getElementById("box1").checked = false;
document.getElementById("box2").checked = false;
}
else if( index == 0 )
{
document.getElementById("box1").checked = true;
}
else
{
document.getElementById("box2").checked = true;
}

Related

How to add background color and foreground color using javascript

the program is to click a colour and select if you want background or foreground then click 'change color' button it works that how it should be but while clicking the value from the variable buttonValue is not coming out of the function.
the value from button value is not coming out please help. The console says the error is
Uncaught TypeError: Cannot read property 'addEventListener' of null
HTML:
<input type="checkbox" name="check" value="background">background</input>
<input type="checkbox" name="check" value="foreground">foreground</input>
<input type="button" value="change color" id='run'>
JS:
var colors = ['red', 'blue', 'green', 'yellow', 'black'];
for(var i=0; i<5; i++){
var button = document.createElement('button');
button.type = 'button';
button.innerText = colors[i];
button.value = colors[i];
button.style.backgroundColor = colors[i];
button.addEventListener('click', change);
document.body.append(button);
}
var buttonValue;
function change(g){
buttonValue = g.target.value;
}
document.getElementById('run').addEventListener('click',AlertMe);
function AlertMe() {
document.getElementsByName('check').forEach( (el) =>{
alert(buttonValue);
if(el.checked === true){
if((el.value) == "background")
{
document.body.style.backgroundColor = buttonValue;
}
else if((el.value) == "foreground")
{
document.body.style.color = buttonValue;
}
}
});
}
this code is working properly as long as you put the code in the header.

Changing background color input when contain word

Hi I have code like below, when I put word "BH" or "bh" my background color will change on yellow. How change javascript code to detect contain word in long text?
For example, when I put text like "Somethink text BH in input" background not change on yellow I would like to detect single letters like BH in long text
function checkFilled() {
var inputVal = document.getElementById("subEmail");
if (inputVal.value == "BH" || inputVal.value == "bh") {
inputVal.style.backgroundColor = "yellow";
}
else{
inputVal.style.backgroundColor = "";
}
}
checkFilled();
<input type="text" id="subEmail" onchange="checkFilled();"/>
You can use .match:
function checkFilled() {
var inputVal = document.getElementById("subEmail");
if (inputVal.value.match("bh|BH")) {
inputVal.style.backgroundColor = "yellow";
}
else{
inputVal.style.backgroundColor = "";
}
}
checkFilled();

select fields with Javascript object

I'm hoping to populate a select field with color options. So far I have this:
function getFruit() {
var x = document.getElementById("myinput").value;
var score;
var picture;
if (x === "Apple") {
score = "A";
picture = "http://exampple.com/assets/apple.jpg";
}
else if (x === "Banana") {
score = "B";
picture = "http://example.com/assets/banana.jpg";
}
document.getElementById("text").innerHTML = score;
document.getElementById("display").image.src = picture;
}
<input type="text" id="text">
<img id="display" />
<select id="color"></color>
but I would like to populate a select field with color options, something like:
if (x === "Apple") {
score = "A";
picture = "http://exampple.com/assets/apple.jpg";
color = "Red" "Green" Blue";
}
Any ideas what format I need to use to add this?
Use an array of colors along with the function add:
.add(new Option(c, value));
var colors = ["Red", "Green", "Blue"];
var sel = document.getElementById('color');
colors.forEach((c, value/*This is the index of this loop*/) => sel.add(new Option(c, value)));
<select id="color"></select>
After
if(x === "Apple") {
score = "A";
picture = "http://exampple.com/assets/apple.jpg";
colors = ["Red", "Green", Blue"];
}
use the reduce method to generate a string of options and assign it to the inner html of color select-box.
document.getElementById("color").innerHTML = color.map((color) => '<option value="' + color+ '">' +color +'</option>').join();
http://jsbin.com/kuyazekivu/edit?html,js,console,output

Changing the color of text with Javascript

I'm trying to make a program where I use a function to change the color of pre-written text using an array and a for loop, depending on what the user inputs when prompted. Here is my code:
// <Student Name> <Student ID> comment must be here.
// This function will change the color of the text to the name of the color you give it.
function changeColor(colorText) {
var text = document.getElementById("colorpar");
text.innerHTML = "<font color=\"" + colorText + "\">The color is " + colorText + ".</font>";
}
// Declare, create, and put values into your color array here
var colors = new Array(5);
colors[0] = "green";
colors[1] = "blue";
colors[2] = "yellow";
colors[3] = "orange";
colors[4] = "red";
// Create a loop that runs 4 times.
// Each time it asks the user for a number between 0 and 4.
// If an invalid input is entered, the color displayed should be black.
// Otherwise display the color at that index in the array.
for (var i = 1; i <= 4; i++) {
var colNumber = window.prompt("Enter a number from 0 to 4:");
if (colNumber == 0 || colNumber == 1 || colNumber == 2 || colNumber == 3 || colNumber == 4) {
changeColor(colors[colNumber]);
} else {
changeColor("black");
}
}
<html>
<head>
<title>Lab 7 Task 2</title>
</head>
<body bgcolor="white">
<h1 id="colorpar">
The color is black.
</h1>
<h1>
</h1>
</body>
</html>
What happens is the text will only show once I've done all of the prompts. It shows the proper color and text and everything, but at the start the "The color is black." doesn't show up, and nothing does until the last prompt is answered.
Note that this is for a beginner class so anything much more advanced than what I have here won't be of much help. I did not write the function, it is there as part of the assignment. I've been at this for hours and can't figure out the issue!
Use SetInterval for this.
check the following code snippet
function changeColor(colorText) {
var text = document.getElementById("colorpar");
text.innerHTML = "<font color=\"" + colorText + "\">The color is " + colorText + ".</font>";
}
// Declare, create, and put values into your color array here
var colors = new Array(5);
colors[0] = "green";
colors[1] = "blue";
colors[2] = "yellow";
colors[3] = "orange";
colors[4] = "red";
// Create a loop that runs 4 times.
// Each time it asks the user for a number between 0 and 4.
// If an invalid input is entered, the color displayed should be black.
// Otherwise display the color at that index in the array.
var x = 0;
var intervalId = setInterval(function() {
if (x == 4) {
clearInterval(intervalId);
}
var colNumber = window.prompt("Enter a number from 0 to 4:");
if (colNumber == 0 || colNumber == 1 || colNumber == 2 || colNumber == 3 || colNumber == 4) {
setTimeout(changeColor(colors[colNumber]), 1000);
} else {
changeColor("black");
}
x++;
}, 100);
<body bgcolor="white">
<h1 id="colorpar">
The color is black.
</h1>
<h1>
</h1>
</body>
Hope this helps

Rainbow Scrolling Text Using <span>

I would like to turn a small paragraph into rainbow text, in which the colors scroll from right to left in an infinite loop using JavaScript. I currently have this paragraph:
<div id="rainbow">
<p id="rtext">
<span id="s1" style="color: red">H</span>
<span id="s2" style="color: blue">e</span>
<span id="s3" style="color: green">l</span>
<span id="s4" style="color: purple">l</span>
<span id="s5" style="color: orange">o</span>
<span id="s6" style="color: magenta">!</span>
</p>
</div>
<div id="actbtn">
<button onclick="activ()">Click for RAINBOW!</button>
</div>`
I am fairly new to JavaScript so I am not sure how to write the activ() function to infinitely scroll the colors.
EDIT:
I would like to thank Ben for the looping script, but now I also need to know how to use the activ() function to change the color of a <span> element. I have tried the following script:
function activ() {
document.getElementById("s1").style.color = 'magenta';
}
But the color will not change. I am trying to keep the script as simple as possible, but also make it work.
FINAL EDIT:
I used Ivan's "UPD Without JQuery" code and added a few colors, and this is what I end up with:
<script>
function EyeVommit() {
document.getElementById("actbtn").style.display = 'none';
'use strict';
var colors = ['red', 'blue', 'green', 'purple', 'orange', 'magenta', 'chartreuse', 'cyan', 'yellow'],
target = document.getElementById('rtext').children,
i,
len = colors.length,
inter = setInterval(function() {
colors.unshift(colors.pop());
for (i = 0; i < len; i++) {
target[i].style.color = colors[i];
}
}, 200);
}
</script>
<div id="table1">
<p id="rtext"> <span id="s1">H</span><span id="s2">e</span><span id="s3">l</span><span id="s4">l</span><span id="s5">o</span><span id="s6">!</span>
<br />
<div id="actbtn">
<button onclick="EyeVommit()">Pabam!</button>
</div>
</p>
The result.
I'm begging you, never, never, never use it in design
<html>
<head>
<title>Price</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script>
function EyeVommit() {
'use strict';
var colors = ['red', 'blue', 'green', 'purple', 'orange', 'magenta'],
$target = $('#rtext span'),
counter,
i,
len = colors.length,
inter;
for (i = 0; i < len; i++) {
$target[i] = $($target[i]);
}
inter = setInterval(function () {
colors.unshift(colors.pop());
for (i = 0; i < len; i++) {
$target[i].css('color', colors[i]);
}
}, 200);
}
</script>
<div id="table1">
<p id="rtext">
<span id="s1">H</span>
<span id="s2">e</span>
<span id="s3">l</span>
<span id="s4">l</span>
<span id="s5">o</span>
<span id="s6">!</span>
</p>
</div>
<script>
EyeVommit();
</script>
</body>
</html>
UPD without jQuery
<script>
function EyeVommit() {
'use strict';
var colors = ['red', 'blue', 'green', 'purple', 'orange', 'magenta'],
target = document.getElementById('rtext').children,
i,
len = colors.length,
inter = setInterval(function () {
colors.unshift(colors.pop());
for (i = 0; i < len; i++) {
target[i].style.color = colors[i];
}
}, 200);
}
</script>
<div id="table1">
<p id="rtext">
<span id="s1">H</span><span id="s2">e</span><span id="s3">l</span><span id="s4">l</span><span id="s5">o</span><span id="s6">!</span>
<button onclick="EyeVommit()">Pabam!</button>
</p>
</div>
If by "Infinitely scroll" you mean create an infinite loop, you could do this.
function blaah(blaah){
//This is where you put all of your rainbow-y code
blaah("blaah");
}
Then you can just call the event through your button.
This code works because everytime the function runs, you call it again. (Second-last line of the function.)
Here's one that will work for any text that you put in the rtext block
Here is a codepen: http://codepen.io/anon/pen/GtwxD
Here's the HTML
<div id="rainbow">
<p id="rtext">Hello! This is some rainbow text!</p>
</div>
<div id="actbtn">
<button>Click for RAINBOW!</button>
</div>
This is the Javascript
$(document).ready(function(){
createSpans();
$('#actbtn').click(activ);
});
$rtxt = $('#rtext');
var text = $rtxt.html() , color;
function createSpans(){
$rtxt.html(' ');
window.colorCount = 0;
window.on = false;
colorPicker();
}
function activ(){
if(!window.on){
window.id = setInterval(colorPicker,100);
window.on = true;
}
else{
clearInterval(window.id);
window.on = false;
}
}
function colorPicker(){
$rtxt.html(' ');
window.colorCount++;
for(var letter = 0; letter < text.length; letter++){
switch ((letter + colorCount) % 6){
case 0 :
color = "red";
break;
case 1 :
color = "orange";
break;
case 2:
color = "green";
break;
case 3 :
color = "purple";
break;
case 4 :
color = "blue";
break;
case 5 :
color = "gold";
break;
default :
color = "black";
break;
}
$rtxt.append('<span style=" color:' + color + ';">' + text[letter] + '</span>');
}
}

Categories

Resources