Reputation: 47
At the moment I'm building a small project for myself and came up with an idea.
Can you use a button as toggle in a form_for to set a bool in the DB? I want to have a green button if the bool is true and a red one if the bool is false.
If I click the button, it should change his color and value and if I submit the form, it should pass that value to the create method.
Any ideas?
Upvotes: 0
Views: 983
Reputation: 1588
So, I think a custom checkbox is the better choice here, but, if you really want to use a button, I would use a hidden checkbox field and apply onclick functions to the button to change the value of a hidden checkbox field. Here is a pen with the general idea http://codepen.io/kaykayyali/pen/WpwvyE
HTML
<input type='checkbox' id='hidden_check_box'>
<button class='red' id='toggle_button' onclick="toggle_checkbox()">
CSS
input[type='checkbox'] {
display: none;
}
button {
width: 20px;
height: 20px;
margin: 5px;
}
.green {
background-color: green;
}
.red {
background-color: red;
}
JS
function toggle_checkbox() {
var checkbox = document.getElementById('hidden_check_box');
var button = document.getElementById('toggle_button');
if (!checkbox.checked) {
checkbox.checked = true;
button.className = 'green';
}
else {
checkbox.checked = false;
button.className = 'red';
}
console.log(checkbox.checked);
}
Upvotes: 0
Reputation: 8552
You can try something like this Orginal link from where code is taken
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {display:none;}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: red;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider {
background-color: #2196F3;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
<!DOCTYPE html>
<html>
<head></head>
<body>
<h2>Toggle Switch</h2>
<label class="switch">
<input type="checkbox">
<div class="slider"></div>
</label>
<label class="switch">
<input type="checkbox" checked>
<div class="slider"></div>
</label><br><br>
<label class="switch">
<input type="checkbox">
<div class="slider round"></div>
</label>
<label class="switch">
<input type="checkbox" checked>
<div class="slider round"></div>
</label>
</body>
</html>
Upvotes: 1