How to Use a Button as a "Checkbox" in form_for_tags?

Currently, I am working on a personal project and have thought of an interesting concept.

Is it possible to use a button as a toggle within a form_for in order to set a boolean value in the database? My goal is to display a green button if the boolean is true and a red button if it is false.

When I click the button, I want it to change color and value. Upon submitting the form, I would like the updated value to be passed to the create method

Do you have any suggestions or ideas on how to achieve this?

Answer №1

For those looking to implement a toggle switch feature, you may find the following code snippet helpful: Link to original source

.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> 

Answer №2

Personally, I believe opting for a custom checkbox is the more favorable route in this scenario. However, if you are adamant about using a button instead, my suggestion would be to incorporate a hidden checkbox field and implement onclick functions on the button to alter the value of said hidden checkbox field. Here's a reference pen showcasing the basic concept 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);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The div element is unable to activate the modal due to tabindex issues

Seeking Assistance with a Specific Scenario I have a specific layout where a div is enclosing an image. The desired functionality is that when the div is clicked with a mouse, a small tooltip modal should appear displaying address information. This can be ...

When using WebDriver's executeScript method, the returned text from an alert is provided rather than the value obtained from a JavaScript

Here is my JavaScript code embedded in an HTML file: function CallMe(a,b){ alert("Hello"); var c = a + b; return c; } Below is my Java code for Selenium WebDriver: JavascriptExecutor executor = (JavascriptExec ...

Utilizing Google+ Snippet and Open Graph Protocol for Enhanced Visibility

I am currently facing an issue with my dynamically built web page where the links shared on Google+ are not showing snippets properly. I have followed the example snippet for article rendering and documentation provided here: https://developers.google.com ...

Why does my node-js API's second endpoint not function properly?

Currently working on my first API project. Everything was going smoothly, until I encountered an issue with my second route, app.route('characters/:characterId'). For some reason, none of the endpoints are functioning, while the first route, app. ...

Comparing jQuery Elements

As per the jQuery documentation, it is stated that "Not All jQuery Objects are Created ===." The documentation also points out an important detail about the unique nature of each wrapped object. This uniqueness holds true even if the objects were created ...

Unusual Vue syntax: deconstructing `state` from `this.$store` with a default value of an

While working on a pre-existing project, I came across some interesting notation in a Vue project utilizing Vuex: const { state = {} } = this.$store; const { orders = {} } = state; This code snippet appears to be creating a local object named "state" tha ...

Revamping the settings page by featuring a single "save changes" button

Is it possible to create a settings.php page where users can update their personal information, such as username, password, and email, all within the same page? I know how to perform these tasks individually, but I'm unsure about integrating different ...

Sending Uint8Array buffer without any null bytes

I am attempting to transfer image data from the Jimp image object to Tesserract (OCR library) using a buffer: image.getBufferAsync('image/png').then((buffer) => { // Buffer here is <Buffer 12 34 56 ... const worker = new TesseractWorke ...

The attempt to create the property 'and_ff' on the string 'and_chr 89' has failed

Encountering an issue with a Lambda function, I receive an error that does not occur when running the same code within an Express app. I'm puzzled. Data returned by caniuse.getLatestStableBrowsers(); [ 'and_chr 89', 'and_ff 86& ...

Embedding a block of PHP code into a JavaScript variable

Query: I am trying to correctly extract HTML from PHP and store it in a variable inside a JavaScript object (specifically the ace-editor's value variable). Challenge: I have a textarea for inputting HTML and CSS, where the HTML is fetched from t ...

Tips for maintaining consistency between server-side Java and client-side JS DTO properties

Greetings, I am in search of a solution or plugin within Eclipse that can ensure synchronization between server-side Java DTO properties and their corresponding client-side JSON elements as the codebase evolves. For instance, in a web application with a Ja ...

The SQL query fails to execute when triggered by window.location.href

Whenever a selection is made, I trigger a Javascript code using the onchange function. I pass along 2 parameters: //capaciteit.php function testfunction(week, id) { window.location.href = "capaciteitberekening.php?week=" + week + "&id=" + id; } The f ...

Jquery Fails to Execute When Clicking on Radio Button

Whenever a user selects a radio button, I want to display an alert box. I have already written the jQuery code to achieve this. Here is my implementation: <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></ ...

Code snippet for adding a div element with an embedded image using JavaScript

I am attempting to create a function that generates three div elements, each containing an image, and then appends them to the body using a for loop. As a beginner in JavaScript, I am struggling with this task. Can anyone please provide guidance on what ...

Calculating the total square footage divided by square feet and the annual rent divided by square feet using Javascript

I need help with running multiple calculations. One of them involves dividing the annual rent by the square feet. However, this calculation fails if a comma or dollar sign is included. I want the rent/sq ft field to display nothing instead of NaN if the fi ...

What is the best way to refresh a React ES6 component following an AJAX response?

I'm a beginner in React and ES6, trying to create a search field that fetches data as the user types. I want to make an AJAX call using the fetch API when the user types at least 3 characters in the field. When I run the fetch snippet code in the brow ...

How can I ensure that server-rendered props are synced with the Redux state in NEXT.js?

Can anyone provide guidance on how to synchronize data fetched using getStaticProps with redux? export async function getStaticProps() { return { props: { trans: "Some data"} }; } ...

What is the best way to eliminate the space underneath a graph?

Despite trying multiple solutions, I'm still struggling to remove the excess blue space below the graph that appears when clicking the submit button. Any insights into what might be causing this issue? JSFIDDLE Below are the CSS styles related to t ...

How can you extract multiple values from a react select component?

return ( <Fragment> <div className="form-group"> <select name="sub" onChange={(e) => { const selectedPackage = e.target.value; setPackage(selectedPackage) }> ...

Seeking help with executing JQuery Ajax functions within a foreach loop

Currently, I am engrossed in the study of programming and endeavoring to construct a website utilizing .Net Core. The predicament at hand pertains to my limited acquaintance with JavaScript while incorporating two JQuery/AJAX functions on my Index page - o ...