How to make interactive option buttons - javascript

This is what I'm trying to achieve: buttons.
I can't figure out how to make the buttons contain form data and have only the selected button post to PHP when I click submit.
Here's what I have so far:
var count = 0;
function setColor(btn, color) {
var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "#4d4d4d"
property.style.color = "#ffffff"
count = 1;
} else {
property.style.backgroundColor = "#ffffff"
property.style.color = '#0000ff'
count = 0;
}
}
<button type="button" id="button1" onClick="setColor('button1', '#101010')">
<input type="radio" name="rooms" value="1">1
<br>
</button>
<button type="button" id="button2" onClick="setColor('button2', '#101010')">
<input type="radio" name="rooms" value="2">2
<br>
</button>
Also help with resetting the other buttons' colors when I click a new option would be appreciated.

The problem is that your buttons have an onclick listener but the listener is also triggered by events on child elements.
So you can click the button but not the checkbox and it changes its color without modifying the value.
You should use an label instead and with CSS3 you can make it without JavaScript.
HTML:
<div>
<input type="checkbox" id="option1" name="rooms" />
<label for="option1">1</label>
</div>
<div>
<input type="checkbox" id="option2" name="rooms" />
<label for="option2">2</label>
</div>
CSS:
input[type="checkbox"]{
display: none;
}
label{
width: 40px;
height: 20px;
color: #4d4d4d;
background: #FFF;
}
input[type="checkbox"]:checked + label{
background: #4d4d4d;
color: #FFF;
}

If you are okay with using just a little bit of JavaScript, then the following will be exactly what you need:
Code:
var buttons = document.querySelectorAll("button[id^=button]");
[].forEach.call(buttons, function(button) {
button.onclick = function() {
/* Remove the 'checked' attribute from the other inputs */
[].forEach.call(buttons, function(each) {
if (button !== each) [].forEach.call(each.children, function(child) {
if (child.nodeName === "INPUT") child.removeAttribute("checked");
});
});
/* Check the child input */
document.querySelector(this.getAttribute("data-check")).setAttribute("checked", "");
/* Remove the 'clicked' attribute from every button */
[].forEach.call(buttons, function(each) {
each.removeAttribute("clicked");
});
/* Add the 'clicked' attribute to the clicked button */
this.setAttribute("clicked", "");
}
});
Notes:
In order to get the look you want, the input itself must be hidden, so we have to use JavaScript to automatically check the input when the button is clicked.
As you can see I have added a data-check attribute to each button. I did that, in order to avoid having to iterate over each child of each button in order to find the inputs and uncheck them. It basically contains the selector of its input child, so that we can use it to find the input immediately with document.querySelector().
Here's a snippet demonstrating the solution:
/* ----- JavaScript ----- */
var buttons = document.querySelectorAll("button[id^=button]");
[].forEach.call(buttons, function(button) {
button.onclick = function() {
/* Remove the 'checked' attribute from the other inputs */
[].forEach.call(buttons, function(each) {
if (button !== each)[].forEach.call(each.children, function(child) {
if (child.nodeName === "INPUT") child.removeAttribute("checked");
});
});
/* Check the child input */
document.querySelector(this.getAttribute("data-check")).setAttribute("checked","");
/* Remove the 'clicked' attribute from every button */
[].forEach.call(buttons, function(each) {
each.removeAttribute("clicked");
});
/* Add the 'clicked' attribute to the clicked button */
this.setAttribute("clicked", "");
}
});
/* ----- CSS ----- */
input[name="rooms"] {
display: none;
}
button {
background-color: white;
border: 1px solid grey;
border-radius: 50%;
color: dodgerblue;
cursor: pointer;
font-size: 1em;
font-weight: 600;
height: 50px;
outline: none;
transition: background-color .3s ease, color .3s ease;
width: 50px;
}
button[clicked] {
color: white;
background-color: grey;
}
<!----- HTML ----->
<div>
<p style = "font-size: 1.3em">Rooms</p>
<div id="button-wrapper">
<button type="button" id="button1" data-check="[name='rooms'][value='1']" clicked>
<input type="radio" name="rooms" value="1" checked/><span>1</span>
</button>
<button type="button" id="button2" data-check="[name='rooms'][value='2']">
<input type="radio" name="rooms" value="2" /><span>2</span>
</button>
<button type="button" id="button2" data-check="[name='rooms'][value='3']">
<input type="radio" name="rooms" value="3" /><span>3</span>
</button>
<button type="button" id="button2" data-check="[name='rooms'][value='4+']">
<input type="radio" name="rooms" value="4+" /><span>4+</span>
</button>
</div>
</div>

Related

Keeping style fixed to input until changed

I have this code at the moment (following on from earliers question):
input[type=submit]:focus {
background-color: yellow;
outline: none;
}
The problem however, is when I click anywhere else on the screen, the background colour reverts to normal. How can I get it to stay and only change if I click another button?
also a further question, how can I get one particular one to default to a colour when the page loads?
at the moment all the colours are black background until you click one, that turns it yellow and then clicking anywhere else on the page, turns that one back to black
pure JS solutions only please
If you want to change the background until it's changed again by another button, use JS to change the input background instead of just changing on focus. Either add an event listener or do it right from the HTML like:
<input type="submit" onclick="this.style.background='yellow';" />
Then do something similar for your other elements that you want to change the colors for. That way the color change will stay until another button changes it.
In your case, you have a css code, that changes the background of button when the button is focused. In order to make a default background of button, you should remove :focus selector.
input[type=submit] {
background-color: blue;
/* All buttons will be blue after page loaded */
outline: none;
}
input[type=submit]:focus {
background-color: yellow;
}
In your case, you need to change the background-color property using JavaScript.
Here is the working example. We set an active class to that button, which was recently clicked and remove active class from other buttons. You can make this in another way, but the logic is like so.
var buttons = document.querySelectorAll('input[type="button"]');
var resetBackgrounds = function() {
for (var i = 0; i < buttons.length; ++i)
buttons[i].className = '';
}
for (var i = 0; i < buttons.length; ++i) {
buttons[i].onclick = function() {
resetBackgrounds();
this.className = 'active';
}
}
input[type="button"] {
background-color: blue;
outline: none;
color: white;
}
input[type="button"].active {
background-color: black;
}
<input type="button" value="Button1" />
<input type="button" value="Button2" />
<input type="button" value="Button3" />
<input type="button" value="Button4" />
Here's a solution in straight jquery:
$('input')
.on('click',function(){
$('input').css('background','')//reset color
$(this).css('background','yellow')//set color
})
input[type=submit]{
background-color: inherit;
outline: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='submit' />
<input type='submit' />
<input type='submit' />
<input type='submit' />
the equivalent in js vanilla:
var inputs = Array.from(document.querySelectorAll('input'))
inputs.forEach(x => x.addEventListener('click', handler))
function handler(e) {
inputs.forEach(x => x.style.background = 'inherit')
e.target.style.background = 'yellow'
}
input[type=submit] {
background-color: inherit;
outline: none;
}
<input type='submit' />
<input type='submit' />
<input type='submit' />
<input type='submit' />

How would I alter this javascript to close the current container when a new container is opened?

I can come up with a really long way around (toggle a opens a and closes b and c, toggle b opens b and closes a and c) but I'm wondering if there is a smarter/quicker option.
http://jsfiddle.net/kbZDv/1/
$(".toggle_container").hide();
$("p.trigger").click(function(){
$(this).toggleClass("active").next().slideToggle("normal");
});
The page: http://orionhistoricalsociety.org/videos/
Remove active class from existing trigger classes, then toggle class as you have been:
$("p.trigger").click(function(){
//removed active class from all p.trigger elements
$("p.trigger").removeClass("active");
//hide shown toggle_containers
$(".toggle_container").hide();
//show requested toggle_container
$(this).toggleClass("active").next().slideToggle("normal");
});
How about using radio buttons?
Here's my idea: CSS can hide the buttons and use a label to provide a way to select them, then the CSS can only show content for "checked" radio buttons.
Example below:
.option_container { margin: 10px 0px; }
.option_container > .block { background:#f0f0f0; }
/* Option styles */
.option_container > label { cursor: pointer; }
.option_container > input[type="radio"] { display: none; }
.option_container > input[type="radio"] ~ .block { display: none; }
.option_container > input[type="radio"]:checked ~ .block { display: block; }
<div class="option_container">
<input id="option1" type="radio" name="option" value="option1" />
<label for="option1">Click here to expand and reveal more information</label>
<div class="block">Content goes here.</div>
</div>
<div class="option_container">
<input id="option2" type="radio" name="option" value="option2" />
<label for="option2">Click here to expand and reveal more information</label>
<div class="block">Content goes here.</div>
</div>
Note: According to MDN, ":checked" is not supported by IE < 9

<button> change color when clicked in HTML?

How do I make a button change to another color when clicked and when clicked again it goes back to its original color? Can I do by using CSS or do I have to use Javascript?
Thanks in advance
This is the HTML code of my buttons.
<div class="H1toH5">
<button class="seatButton">H1</button>
<button class="seatButton">H2</button>
<button class="seatButton">H3</button>
<button class="seatButton">H4</button>
<button class="seatButton">H5</button>
</div>
Pure CSS
Change your button to another element (like span)
Use a label and checkbox to control the toggle status
Use :checked CSS selector and + sibling selector
.H1toH5 input { display: none; }
.H1toH5 .seatButton { padding: 5px; border: 1px solid #ccc; background: yellow; }
.H1toH5 input:checked + .seatButton { background: red; }
<div class="H1toH5">
<label>
<input type="checkbox" />
<span class="seatButton">H1</span>
</label>
<label>
<input type="checkbox" />
<span class="seatButton">H1</span>
</label>
<label>
<input type="checkbox" />
<span class="seatButton">H1</span>
</label>
<label>
<input type="checkbox" />
<span class="seatButton">H1</span>
</label>
<label>
<input type="checkbox" />
<span class="seatButton">H1</span>
</label>
</div>
How do I make a button change to another color when clicked and when clicked again it goes back to its original color? Can I do by using CSS
Try utilizing css :focus pseudo class , background-color
button {
background-color:yellow;
}
button:focus {
background-color:orange;
}
<div class="H1toH5">
<button class="seatButton">H1</button>
<button class="seatButton">H2</button>
<button class="seatButton">H3</button>
<button class="seatButton">H4</button>
<button class="seatButton">H5</button>
</div>
no just the one that is clicked, but i want to be able to click on
many buttons not just one
var elems = document.getElementsByClassName("seatButton");
for (var i = 0; i < elems.length; i++) {
elems[i].onclick = function() {
var color = window.getComputedStyle(this, null)
.getPropertyValue("background-color");
this.style.backgroundColor = color === "rgb(255, 255, 0)"
? "rgb(255, 165, 0)" : "rgb(255, 255, 0)";
};
};
button {
background-color:yellow;
}
<div class="H1toH5">
<button class="seatButton">H1</button>
<button class="seatButton">H2</button>
<button class="seatButton">H3</button>
<button class="seatButton">H4</button>
<button class="seatButton">H5</button>
</div>
You can do this with css a ::before pseudo element and the html checkbox input tag
input.toggle-btn {
visibility: hidden;
}
input.toggle-btn::before {
content: attr(value);
display: inline-block;
padding: 5px;
background: #fff;
font-size: 14pt;
color: #aaa;
border-radius: 5px;
border: 1px solid #aaa;
visibility: visible;
}
input.toggle-btn:checked::before {
background: rgb(50,150,250);
color: #eee;
border-color: #eee;
}
<input class="toggle-btn" type="checkbox" value="Hello">
This code will toggle a specific class when you click on it. If you click on the button again it will then return to it's original state.
$('.seatButton').click(function () {
$(this).toggleClass('activeClass');
});
Or just use the CSS Pseudo selected as people have specified above. There are many ways to achieve what you want!
No. You need to add/remove a class with javascript. To make #tpie feel better about himself, here is the code for that. Using jQuery:
$('.seatButton').on('click', function(){
$(this).toggleClass('is-active');
});

Apply CSS to disabled input button

<input type="button" value="Share" id="buttonShareMap" style="float:right; width:68px;" disabled="disabled"/>
/* Only enable 'SHARE' btns if a checkbox is selected */
var checkboxes = $("input[type='checkbox']"),
submitButtShare = $("#buttonShareMap");
checkboxes.click(function () {
submitButtShare.attr("disabled", !checkboxes.is(":checked"));
});
This code works fine, only enabling the button if a check box is clicked. However I want to use the css classes 'class="edit red btn"', and although the functionality is still working the button appears visible.
I would like to add one css class if button is enabled and another if it is disabled...How Can I do this? thanks
You can add a new css class here:
submitButtShare.attr("disabled", !checkboxes.is(":checked")).toggleClass('disabled');
now in the css you can use this:
#buttonShareMap.disabled{
background:#c5c5c5;
color:#ddd;
}
checkout the sample demo:
$(':checkbox').change(function() {
$('#buttonShareMap').prop('disabled', this.checked).toggleClass('disabled');
});
.red {
color: red;
background:#0ff;
}
#buttonShareMap.disabled {
background: #c5c5c5;
color: #ddd;
cursor: not-allowed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='button' id='buttonShareMap' class='red' value='buttonShareMap' />
<input type='checkbox' />
you can set background color for disable elements, by using below code.
#buttonShareMap:disabled {
background: #f00;
}
Just check the button disabled attr or just the checkbox checked value and set classes accordingly. Below I have used the checkbox state.
checkboxes.click(function () {
submitButtShare.attr("disabled", !checkboxes.is(":checked"));
if(checkboxes.is(":checked"))
{
submitButtShare.addClass('ifButtonEnabled')
.removeClass('ifButtoDisabled');
}
else
{
submitButtShare.addClass('ifButtoDisabled')
.removeClass('ifButtonEnabled');
}
});
Helo,
I have made an example for you: http://jsfiddle.net/o82tfxrb/1/
js:
$(document).ready(function(){
$('#ck').on('change', function(){
if ($(this).is(':checked')){
$('#buttonShareMap').removeClass('red')
.addClass('blue');
}else{
$('#buttonShareMap').removeClass('blue')
.addClass('red');
}
});
});
html:
<input type="checkbox" id="ck" />
<input type="button" class="red" value="Share" id="buttonShareMap"/>
css:
.red{
background-color:red;
}
.blue{
background-color:blue;
color: white;
}
What I am doing is check everytime the user change the checkbox and then I add a class.
I hope it's helps!
Here is the HTML
<input disabled="disabled" class="btn btn-blue span3" type="submit" value="Change">
Here is the CSS
input[disabled].btn:hover,input[disabled].btn:hover,input[disabled].btn:focus{
color:yellow}

Images as radio button

I'm trying to achieve this but it doesn't work.
Here it is the CSS sheet:
.input_hidden {
position: absolute;
left: -9999px;
}
.selected {
background-color: #000000;
}
#carte label {
border: inline-block;
cursor: pointer;
}
#carte label img {
padding: 3px;
}
the HTML part:
<div id="carte">
Select a card:<BR>
<input type=radio name="carte" id="cart1" class='input_hidden' />
<label for="cart1">
<img src="cart1.jpg" alt="carte1" />
</label>
<input type=radio name="carte" id="cart2" class='input_hidden' />
<label for="cart2">
<img src="cart1.jpg" alt="carte2" />
</label>
<input type=radio name="carte" id="cart3" class='input_hidden' />
<label for="cart3">
<img src="cart3.jpg" alt="carte3" />
</label>
</div>
and the javascript:
$('#carte label').click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
});
When I assign the selected class to an image it is ok, I see it with the black border. but it seems the javascript part to assign the class doesn't work.
I there any other way to assign the correct classes to the images?
Thanks for your support.
Are you sure you want to use jQuery?
With sane browsers you can solve it with pure css: http://jsfiddle.net/VSR86/4/
HTML:
<div id="carte">
<label>
<input type="radio" name="carte" value="cart1" >
<img src="http://placekitten.com/100/100">
</label>
...
CSS:
label input + img {
border: 10px solid transparent;
}
label input:checked + img {
border: 10px solid blue;
}
Of course some javascript fallback will be necessary for IE8 and older.
https://developer.mozilla.org/en-US/docs/Web/CSS/:checked
IE8 fix
Updated CSS:
label input.checked + img,
label input:checked + img {
border: 10px solid blue;
}
JS fallback:
if(/* this browser is IE8 or worse */){
$(document).on('click','label:has(input[type="radio"])',function(){
var $r = $(this).find('input');
adjustRadio( $r.attr('name'), $r.val(), 'checked');
});
}
function adjustRadio( name, value, className ){
// wait for other event handlers to run
setTimeout( function(){
$('input[type="radio"][name="'+name+'"]').each( function(){
var $r = $(this);
$r.toggleClass( className, $r.val() === value );
});
},1);
}
You could use the toggleClass function for some simplicity :)
http://api.jquery.com/toggleClass/
Since people are picky, here's a fiddle for you sir
http://jsfiddle.net/8B3SW/1/
$('#carte label').click(function(){
$(this).toggleClass('selected').siblings().removeClass('selected');;
});

Categories

Resources