Buttons display progress - javascript

I'm doing a project for parent with a newborn Child, where they can progress in their learning taking care of their Child. This will be shown with buttons, and when a stage is complete, it will change the color on that button.
My code so far looks like this:
To change the buttons color to green.
var count = 1;
function setColor(btn, color) {
var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "#FFFFFF"
count = 1;
}
else {
property.style.backgroundColor = "#7FFF00"
count = 0;
}
}
<div class="container">
<h2>Change diaper</h2>
<div class="well">
<input type="button" id="button" value = "Instructed" style= "color:black" onclick="setColor('button', '#101010')";/>
<input type="button" id="button" value = "Done with help" style= "color:black" onclick="setColor('button', '#101010')";/>
<input type="button" id="button" value = "Done by yourself" style= "color:black" onclick="setColor('button', '#101010')";/>
</div>
</div>
When I Click the first button "Instructed" the color change to green (As I want it to). But when I click anyother button, the first button once again goes green and the other goes blue?
How can I fix it so whatever button they click on, will be colored green?

You gave every button the same id - an id should be identifying, which in this case it isn't. Your code here, takes the first element with the id button which is why the first button changes everytime.
Either use different ids for each individual button, or access the clicked element itself through the event-variable.
You also have only one count-variable, which won't work with multiple buttons. Imagine you pressing the first button => count is now 1. You then press the second button, it wouldn't turn green, as count is already 1.
You should probably store that information on the element itself, probably with a data-count-attribute.
Here is a working example:
function setColor(element) {
if(!element.hasAttribute('data-count')){
element.setAttribute('data-count', 1);
}
var count = element.getAttribute('data-count');
if(count == 0){
element.style.backgroundColor = '#ffffff';
element.setAttribute('data-count', 1);
}else{
element.style.backgroundColor = '#7fff00';
element.setAttribute('data-count', 0);
}
}
<div class="container">
<h2>Change diaper</h2>
<div class="well">
<input type="button" value = "Instructed" style= "color:black" onclick="setColor(this)";/>
<input type="button" value = "Done with help" style= "color:black" onclick="setColor(this)";/>
<input type="button" value = "Done by yourself" style= "color:black" onclick="setColor(this)";/>
</div>
</div>

So lets remove those duplicate ID's, and then we can actually pass the element into the function directly so we don't need to grab it by it's ID.
Then instead of using a count variable, we store value on the actual element in a data attribute so that it's state is stored on the element itself.
function setColor(element) {
if (element.getAttribute('data-done') === "0") {
element.style.backgroundColor = "#7FFF00"
element.setAttribute('data-done', "1");
} else {
element.style.backgroundColor = "#FFFFFF"
element.setAttribute('data-done', "0");
}
}
<div class="container">
<h2>Change diaper</h2>
<div class="well">
<input type="button" id="button1" value="Instructed" style="color:black" onclick="setColor(this)" data-done="0" />
<input type="button" id="button2" value="Done with help" style="color:black" onclick="setColor(this)" data-done="0" />
<input type="button" id="button3" value="Done by yourself" style="color:black" onclick="setColor(this)" data-done="0" />
</div>
</div>
Although perhaps the most semantic way would be to use classes and add an event listener:
// Grab all the buttons by their class
var btns = document.querySelectorAll('.btn-diaper');
// Loop through the buttons
for (var i = 0; i < btns.length; i++) {
// Assign a click listener to each button
btns[i].addEventListener("click", function(event) {
var el = event.toElement;
// Toggle the "active" class, which changes the button styling
if (el.classList.contains('active')) {
el.classList.remove('active');
} else {
el.classList.add('active');
}
});
}
.btn-diaper {
color: black;
background-color: #fff;
}
.btn-diaper.active {
background-color: #7fff00;
}
<div class="container">
<h2>Change diaper</h2>
<div class="well">
<input class="btn-diaper" type="button" id="button1" value="Instructed" />
<input class="btn-diaper" type="button" id="button2" value="Done with help" />
<input class="btn-diaper" type="button" id="button3" value="Done by yourself" />
</div>
</div>

Related

Making div tag invisible on page load and display several div tags on button click

I want to make a div tag invisible when the page loads and make it visible everytime a button is clicked. This is what I have on my page:
<div id="realProp1">
<input name="FirstName[0]" class="form-control" />
</div>
<div id="realProp2">
<input name="FirstName[1]" class="form-control" />
</div>
<div id="realProp3">
<input name="FirstName[2]" class="form-control" />
</div>
<button type="button" onclick="AddItem()" class="btn btn-primary">Add Item</button>
Whenever AddItem button is clicked, I want to display one Div tag/item so if I click "Add Item" button, I want to make visible only div tag "realProp1", now if I click "AddItem" button again, I want to make visible "realProp2" div tag. Below is what I have, the code is working for one div tag, but not for several div tags:
<script>
window.onload = function () {
document.getElementById("realProp1").style.display = 'none';
document.getElementById("realProp2").style.display = 'none';
document.getElementById("realProp3").style.display = 'none';
};
function Additem() {
document.getElementById("realProp1").style.display = "";
};
</script>
How can I make one div tag visible at each button click.
You can use :eq() to compare which div to show and save some variable for holding the last count value or you can just use $("div[id^=realProp]").filter(":hidden").first().show() for filtering the hidden divs and showing first div always.
Demo Code :
$('div[id^=realProp]').hide();
var count = 0;
$('.show_div').on('click', function() {
$('div[id^=realProp]:eq(' + count + ')').show(); //show div
count++; //for next div to show
//or without count ..use below
//show first div..by filtering hidden divs
//$("div[id^=realProp]").filter(":hidden").first().show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="realProp1">
<input name="FirstName[0]" class="form-control" />
</div>
<div id="realProp2">
<input name="FirstName[1]" class="form-control" />
</div>
<div id="realProp3">
<input name="FirstName[2]" class="form-control" />
</div>
<button type="button" class="btn btn-primary show_div">Add Item</button>
Without jquery :
var length = document.querySelectorAll("div[id^='realProp']").length;
var count = 1; //for holding last visible div count
function AddItem() {
if (count <= length) {
document.getElementById("realProp" + count).style.display = "block"; //show..
count++;
} else {
console.log("No more divs")
}
};
div[id^='realProp'] {
display: none
}
<div id="realProp1">
<input name="FirstName[0]" class="form-control" />
</div>
<div id="realProp2">
<input name="FirstName[1]" class="form-control" />
</div>
<div id="realProp3">
<input name="FirstName[2]" class="form-control" />
</div>
<button type="button" onclick="AddItem()" class="btn btn-primary">Add Item</button>
let count = 1;
window.onload = function() {
document.getElementById("realProp1").style.display = 'none';
document.getElementById("realProp2").style.display = 'none';
document.getElementById("realProp3").style.display = 'none';
};
function AddItem() {
for (let i = 1; i < 4; i++) {
document.getElementById("realProp" + i).style.display = "none";
}
document.getElementById("realProp" + count).style.display = "";
if (count <3 ){
count++;
} else {
count = 1;
}
};
<div id="realProp1">
<input name="FirstName[0]" class="form-control" />
</div>
<div id="realProp2">
<input name="FirstName[1]" class="form-control" />
</div>
<div id="realProp3">
<input name="FirstName[2]" class="form-control" />
</div>
<button type="button" onclick="AddItem()" class="btn btn-primary">Add Item</button>

Detect innerHTML of clicked button

I am trying to make the innerHTML of a single button (amongst various buttons) the value of an input.
I have an empty div inside a form and six buttons (each with the same class).
<form>
<div id='wrapper'></div>
<button type='submit'>Submit</button>
</form>
<div class="col-lg-6 Div1">
<button class="form-button" onclick="addForm()">Button 1</button>
<button class="form-button" onclick="addForm()">Button 2</button>
<button class="form-button" onclick="addForm()">Button 3</button>
</div>
<div class="col-lg-6 Div2">
<button class="form-button" onclick="addForm()">Button 4</button>
<button class="form-button" onclick="addForm()">Button 5</button>
<button class="form-button" onclick="addForm()">Button 6</button>
</div>
And then I have a dynamically added inputs, a button and a div. The inputs and buttons gets added into the div (.innerDiv) which get's added inside the #wrapper div (in the html code). The reason is so that the remove button can remove everything from it's parent element without removing all the dynamically added tags.
i = 1;
addForm() {
if(i < Infinity) {
var innerDiv = document.createElement('div');
innerDiv.classList = 'innerDiv' + i;
$('.wrapper').append(innerDiv);
//This adds a fixed input
var dynamicInput = document.createElement('input');
dynamicInput.type = 'text';
dynamicInput.name = 'dynamicInputName' +i;
dynamicInput.disabled = true;
dynamicInput.classList = 'dynamicInputClass';
$(".form-button").click(function() { dynamicInput.value = this.innerHTML; }); //Gives the innerHTML of the button that was clicked as the value of the input
$('.innerDiv' + i).append(dynamicInput);
var anotherInput = document.createElement('input');
anotherInput.type = 'text';
anotherInput.name = 'anotherInput' +i;
anotherInput.classList = 'anotherInputClass';
anotherInput.placeholder = 'Write name here';
$('.innerDiv' + i).append(anotherInput);
var removeButton = document.createElement('button'); //This removes one element inside a parent div.
removeButton.type = 'button';
removeButton.classList = 'remove';
removeButton.innerHTML = '-';
removeButton.onclick = function () {
this.parentElement.remove();
}
$('.innerDiv').append(removeButton);
i++;
}
}
I've fixed the function for the dynamicInput to what was suggested to me by s.Bergmann. So whenever a button with the class of .form-button is clicked, all the above stiff will be added and the dynamicInput will have a fixed value of the button that was clicked. If I click Button 5 and then Button 2, in code, it will look a little something like this:
<form>
<div id='wrapper'>
<div class='innerDiv1'>
<input type='text' name='dynamicInputName1' class='dynamicInputClass' value='Button 2' disabled>
<input type='text' name='anotherInput1' class='anotherInputClass' placeholder='Write name here'>
<button type='button' class='remove'>-</button>
</div>
<div class='innerDiv2'>
<input type='text' name='dynamicInputName2' class='dynamicInputClass' value='Button 2' disabled>
<input type='text' name='anotherInput2' class='anotherInputClass' placeholder='Write name here'>
<button type='button' class='remove'>-</button>
</div>
</div>
<button type='submit'>Submit</button>
</form>
As you can see, each button added one div, with the two inputs and the button. However, both inputs that were created from the dynamicInput have the same value (Button 2.). The idea is, if I press Button 5 first the first dynamicInput should have a value = 'Button 5' and if I then press Button 2, the second dynamicInput should have a value = 'Button 2' (These inputs are the first input of each div).
I'm not sure this is what you're going for,
but it might nudge you in the right direction.
It seems that onclick on a .form-button two things should happen:
it should create a dynamic input element
addForm() should be called // or perhaps addForm is what creates the input element?
If i were you, i'd reconsider the need for that "dynamic element". why not just use the actual button clicked?
anyway...
$(".form-button").click(function () { // replaces all the onlick=
addForm(this);
var dynamicInput = document.createElement('input');
dynamicInput.type = 'text';
dynamicInput.name = 'dynamicInputName';
dynamicInput.disabled = true;
dynamicInput.classList = 'dynamicInputClass';
dynamicInput.value = this.innerText;
console.log("Dynamic input", dynamicInput.value);
});
function addForm (formButton) { // dummy function? unclear what it's used for.
console.log("Form Button:", formButton)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-6 Div1">
<button class="form-button"> Button 1</button>
<button class="form-button">Button 2</button>
<button class="form-button">Button 3</button>
</div>
<div class="col-lg-6 Div2">
<button class="form-button">Button 4</button>
<button class="form-button">Button 5</button>
<button class="form-button">Button 6</button>
</div>

How to get the Value in the labels for the 2 independent buttons?

I have two buttons with a single label like the below. The two buttons were independent.
<label for="buttons" class ="val">0</label>
<input class="btn btn-primary button1" type="button" value="button1" onclick="changeLabel()">
<input class="btn btn-primary button2" type="button" value="button2">
When I click the button1 1sttime, the Value in the label should be 1, for the 2nd time, the value in the label should be 2 and for the 3rd time, the value in the label should be 3. When I click the button1 for the 4th time, the value should again go back to 0. Like 0,1,2,3,0,1.....
The same should be the case for the button2 too. But, If i press the button1 2times. Then the Value in the label should be 2.At the same time, if I press the button2 for 3times the value in the label should change to 3 immediately.
Both the buttons, should be independent. The Values should be different for each buttons when they were clicked.
(".button1").click(function(){
var value = $('.val').html(parseInt($('.val').html())+1);
});
$(".button2").click(function(){
$('.val').html(parseInt($('.val').html())+1);
});
I couldn't do so. The value should return to 0 after clicking the buttons 3 times.
here is my codepen, https://codepen.io/Davi9/pen/LYLqWKx
could anyone please help?
Many thanks.
If you want to reset the counter to 0 when it reach 3, then try this:
$(".button1").click(function() {
var v = +$(".val").html();
$(".val").html(v > 2 ? 0 : v + 1);
});
Demo
$(".button1").click(function() {
var v = +$(".val").html();
$(".val").html(v > 2 ? 0 : v + 1);
});
$(".button2").click(function() {
var v = +$(".val").html();
$(".val").html(v > 2 ? 0 : v + 1);
});
body {
font-family: system-ui;
background: #f06d06;
color: white;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="container">
<div class="row ">
<div class="col-md-6">
<br />
<label for="buttons" class="val">0</label>
<br />
<input class="btn btn-primary button1" type="button" value="button1">
<input class="btn btn-primary button2" type="button" value="button2">
</div>
</div>
</div>
</body>
Check the value of the label, if its greater than 3, set it to zero, somthing like
(".button1").click(function(){
incr();
});
$(".button2").click(function(){
incr();
});
function incr() {
var val = parseInt($('.val').html());
val=val+1;
if(val > 3)
val = 0;
$('.val').html(val);
}

JavaScript function() for buttons disabled/enabled

I have two buttons in my HTML:
<form>
<input type="button" id="button1" value="Clickable" onClick="switchButton()">
<input type="button" id="button2" value="Not Clickable" onClick="switchButton2()" disabled="true">
</form>
I want to write a function() in JavaScript for when I click on button1 it should be disabled and change it's value to "not clickable" and button2 should be enabled and change it's value to "clickable" and the other way around.
I have written two functions but they aren't correct and I am very new to JavaScript. This is my functions():
function switcher() {
var btn = document.getElementById("knapp1");
btn.disabled = true;
}
function switcher2(){
var btn2 = document.getElementById("knapp2");
btn2.enabled = true;
}
You have a problem with the name of your function : switchButton() in your html and switcher in your js, the id are different too and enabled is not an html property. You can achieve what you want with only one function :
function switchButton(btn1, btn2) {
var btn1 = document.getElementById("button"+btn1);
var btn2 = document.getElementById("button"+btn2);
btn1.disabled = true;
btn1.value = "not clickable";
btn2.disabled = false;
btn2.value = "clickable";
}
<form>
<input type="button" id="button1" value="Clickable" onClick="switchButton(1,2)">
<input type="button" id="button2" value="Not Clickable" onClick="switchButton(2,1)" disabled="true">
</form>
You should try to avoid have this duplicate logic that make the same, is very hard to maintain, I recommend to you instead use this:
function clickButton(e) {
const currentBtn = document.getElementById(e);
const otherBtn = document.getElementById(e === "knapp2"? "knapp1": "knapp2");
currentBtn.disabled = true;
otherBtn.disabled = false;
currentBtn.value="Not Clickable"
otherBtn.value="Clickable"
}
<form>
<input type="button" id="knapp1" value="Clickable" onClick="clickButton('knapp1')">
<input type="button" id="knapp2" value="Not Clickable" onClick="clickButton('knapp2')" disabled>
</form>

javascript function on multiple buttons

I have three buttons. I would like them to change colour when pressed, and back to no colour when pressed again.
I found this code on stackoverflow that allows me to almost do it however, it only works on one button, the other two are not affected.Also, when I pressed one of the other two buttons, the first button changes colour. I tried changing ID's on the buttons, adding another script with different getElementById() ID's but nothing works.
Do I need more than one function to achieve what I want?
The code I am using is below.
var count = 1;
function setColor(btn, color) {
var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "#FFFFFF";
count = 1;
} else {
property.style.backgroundColor = "#E68352";
count = 0;
}
}
<head>
<link rel="stylesheet" type="text/css" href="styles/main.css"/>
</head>
<body>
<input type="button" id="button" value = "A-D" style= "color:black" onclick="setColor('button', '#101010')";/>
<input type="button" id="button" value = "E-H" style= "color:black" onclick="setColor('button', '#101010')";/>
<input type="button" id="button" value = "E-H" style= "color:black" onclick="setColor('button', '#101010')";/>
</body>
Usually, when you write inline event handler you may take advantage of:
this: current element: When code is called from an in–line on-event handler, its this is set to the DOM element on which the listener is placed:
event: event element object
Therefore, change:
onclick="setColor('button', '#101010')"
with:
onclick="setColor(this, event, '#101010')"
So your code can be rewritten as:
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? 'rgb(' +
parseInt(result[1], 16) + ', ' +
parseInt(result[2], 16) + ', ' +
parseInt(result[3], 16) + ')'
: null;
}
function setColor(btnEle, evt, color) {
if (btnEle.style.backgroundColor == hexToRgb("#E68352")) {
btnEle.style.backgroundColor = "#FFFFFF"
}
else {
btnEle.style.backgroundColor = "#E68352"
}
}
<input type="button" id="button1" value = "A-D" style= "color:black" onclick="setColor(this, event, '#101010')";/>
<input type="button" id="button2" value = "E-H" style= "color:black" onclick="setColor(this, event, '#101010')";/>
<input type="button" id="button3" value = "E-H" style= "color:black" onclick="setColor(this, event, '#101010')";/>
You should have uniques ID
You can use classList.toggle("yourClass") instead of using a count
var buttons = document.getElementsByClassName("button");
for (let i = 0, l = buttons.length; i < l; i++) {
buttons[i].addEventListener('click', function() {
buttons[i].classList.toggle('active');
})
}
.active {
background-color: #E68352 !important;
}
.button {
background-color: #FFFFFF;
}
<input type="button" id="button1" class="button" value="A-D" />
<input type="button" id="button2" class="button" value="E-H" />
<input type="button" id="button3" class="button" value="E-H" />
Set a class on the buttons, and then loop through the buttons and add an event listener to each of them:
EDIT: I see you are using an onclick handler, which I didn't notice at first; so this answer might not be as useful as I thought. You should definitely use different IDs though if you use that approach.
<button class="button" ... >
var buttons = document.getElementsByClassName('button')
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function() {
// Do your button things.
})
}
IDs should be unique inside the document. Like this:
<input type="button" id="button1" value="A-D" style="color:black" onclick="setColor('button1', '#101010')" ;/>
<-- here ^ here ^ -->
<input type="button" id="button2" value="E-H" style="color:black" onclick="setColor('button2', '#101010')" ;/>
<-- here ^ here ^ -->
<input type="button" id="button3" value="E-H" style="color:black" onclick="setColor('button3', '#101010')" ;/>
<-- here ^ here ^ -->
<!DOCTYPE html>
<html>
<head>
<script>
var count = 1;
function setColor(btn, color) {
var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "#FFFFFF"
count = 1;
} else {
property.style.backgroundColor = "#E68352"
count = 0;
}
}
</script>
<link rel="stylesheet" type="text/css" href="styles/main.css" />
</head>
<body>
<input type="button" id="button1" value="A-D" style="color:black" onclick="setColor('button1', '#101010')" ;/>
<input type="button" id="button2" value="E-H" style="color:black" onclick="setColor('button2', '#101010')" ;/>
<input type="button" id="button3" value="E-H" style="color:black" onclick="setColor('button3', '#101010')" ;/>
</body>
</html>
IDs need to be unique but you do not need them here
Give the buttons a class and use toggle the classList
window.onload=function() {
var buts = document.querySelectorAll(".but");
for (var i=0;i<buts.length;i++) {
buts[i].onclick=function() {
this.classList.toggle("clicked");
}
}
}
.but {background-color:black}
.clicked { background-color:#E68352; }
<input type="button" value="A-D" class="but" />
<input type="button" value="E-F" class="but" />
<input type="button" value="G-H" class="but" />
dont use numbers, use this instead
http://codepen.io/animhotep/pen/qRwjeX?editors=0010
var count = 1;
function setColor(btn, color) {
if (count == 0) {
btn.style.backgroundColor = "#FFFFFF"
count = 1;
}
else {
btn.style.backgroundColor = "#E68352"
count = 0;
}
}
Roberto, as Ibrahim correctly pointed out, the problem is that you are using the same ID for all buttons. When javascript executes this code:
var property = document.getElementById(btw);
it will always return the first element with the ID specified. One solution is choosing a different ID for each button and updating the corresponding onclick code. Another solution could be the one below, in which you do not need to specify IDs at all and the function setColor could be used for any element.
<!DOCTYPE html>
<html>
<head>
<script>
var count = 1;
function setColor(element, color) {
if (count == 0) {
el.style.backgroundColor = "#FFFFFF"
count = 1;
}
else {
el.style.backgroundColor = "#E68352"
count = 0;
}
}
</script>
<link rel="stylesheet" type="text/css" href="styles/main.css"/>
</head>
<body>
<input type="button" value = "A-D" style= "color:black" onclick="setColor(this, '#101010')";/>
<input type="button" value = "E-H" style= "color:black" onclick="setColor(this, '#101010')";/>
<input type="button" value = "E-H" style= "color:black" onclick="setColor(this, '#101010')";/>
</body>
</html>
Note the use of the this variable as the first argument for setColor. In each of the buttons, the corresponding this will point to the element where it is defined.
Hope it helps.
You just need little bit of modification.
See the working code.
function setColor(btn, color) {
var elem = document.getElementById(btn);
if (elem.hasAttribute("style")) {
if (elem.getAttribute("style").indexOf("background-color:") == -1) {
elem.style.backgroundColor = color;
} else {
elem.style.backgroundColor = "";
}
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles/main.css" />
</head>
<body>
<input type="button" id="button1" value="A-D" style="color:black" onclick="setColor('button1', '#E68352')" ;/>
<input type="button" id="button2" value="E-H" style="color:black" onclick="setColor('button2', '#E68352')" ;/>
<input type="button" id="button3" value="E-H" style="color:black" onclick="setColor('button3', '#E68352')" ;/>
</body>
</html>

Categories