Top method for displaying radio buttons as switchable buttons within a web form

I want to customize the appearance of my radio buttons on a form to make them look like toggle-able HTML buttons, similar to the examples shown in these Bootstrap examples. By using Flask, Bootstrap, and jinja2, I've successfully converted my radio buttons to resemble "buttons". The relevant section of my form currently displays like this:

{{ form.setting.label }}<br>           
{% for subfield in form.setting %}
    <tr>
        <td>{{ subfield(class_="no_rad") }}</td>
        <td>{{ subfield.label(class_="btn btn-primary") }}</td>
    </tr>
{% endfor %}<br>

In this code, 'subfield' represents the radio button itself. The class_="no_rad" attribute applies a CSS class that I created with display: none;. Similarly, the subfield.label is given a Bootstrap CSS class to simulate a button-like appearance. While these buttons are "selectable" (they have data associated with them), there are a couple of additional things I would like to achieve:

  • I want the appearance of the button to change when clicked, indicating it is toggled
  • I'd like the buttons to be deselected if clicked again (unlike traditional radio buttons)

I understand that achieving this functionality may involve using jQuery, but I'm unsure of how to get started with that.

Answer №1

After much trial and error, I've managed to find a solution to achieving my desired outcome. Instead of relying on manually coded Jquery, I utilized more bootstrap functionality, following the examples linked in my original question. This involved integrating a rather messy bunch of src tags into base.html:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8cac7c7dcdbdcdac9d8e89c86e8698">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>    
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

Additionally, I incorporated a mix of Bootstrap and jinja2 syntax in the displayed page:

{{ form.setting.label }}<br>           
<div class="btn-group-toggle" data-toggle="buttons">
    {% for subfield in form.setting %}
        <label class="btn btn-primary">
            {{ subfield}} {{ subfield.label(style="cursor:pointer;") }}
        </label>
    {% endfor %}<br> 
    {% for error in form.setting.errors %}
        <span style="color: red;">[{{ error }}]</span>
    {% endfor %}
</div>

Although the buttons now appear activated upon clicking, there are still some peculiar rendering quirks I encountered:

  • I had to manually add
    style="cursor:pointer;"
    to subfield.label to ensure the cursor changes when hovering over the button's label, as well as around the label.
  • The buttons themselves seem taller than expected, a styling issue that can be addressed through CSS adjustment.
  • Part of my form is dynamic and updates based on radio button values using jquery. However, under the Bootstrap styles, my script only recognizes clicks on the first button within the div. Update: I managed to resolve this by following guidance from this helpful thread.

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

Unable to access the current state within an asynchronous function in React.js

I have encountered an issue with updating state in the top-level component (App) and accessing the updated state in an asynchronous function defined within useEffect(). Here are more details: The problem arises when I try to retrieve the state of the cons ...

Merging scripts to minimize HTTP requests - The Takeover of the Body Swappers

For my website design, I've implemented the Invasion Of The Body Switchers script from brothercake.com. This script involves loading three separate js files in the header. I'm looking to optimize my site by reducing the number of HTTP requests a ...

Error thrown due to inability to map imported JSON data

Displayed below is a snippet of data stored in the data.json file: [ {"id": 23, "name": "Good!", "state": "OK"}, {"id": 24, "name": "Not good...", "state": " ...

Retrieve the Typescript data type as a variable

I have the following components: type TestComponentProps = { title: string; } const TestComponent: React.FC<TestComponentProps> = ({ title, }) => { return <div>TestComponent: {title}</div>; }; type TestComponent2Props = { bod ...

Trouble with displaying label in PDF post HTML conversion using iText html2pdf

Software Versions: html2pdf v2.0.1 iText 7.1.1 The HTML label that spans the width of the page is as follows: <label class="test">Patient</label> CSS Styling: .test { display: block; font-weight: bold; color: #009fd1; font ...

Guide to waiting for API responses with redux-saga

I have a React-Typescript app with backend calls using React Saga. I'm facing an issue where when one of my frontend functions makes a backend call, the next function starts executing before the previous one finishes. Currently, I'm using the SE ...

The integration of VueJS with Axios and the Google Maps API

Currently following [this][1] guide to develop a Google Map and now I am looking to execute a GET request with Axios: axios.get("http://localhost:8080/mapjson").then(function(response) { }) in order to integrate the information from my JSON file into the ...

Implementing ng-if with asynchronous functions: A step-by-step guide

The objective here is to display an image in a template only if the ratio of its dimensions is greater than 2. <img class="main-img" ng-if="showImage($index)" ng-src="{{item.img}}"> Implementation: $scope.showImage = function(index) { var img ...

Prevent JavaScript from sending a POST request to a specific URL

Currently facing Cross Site Scripting (XSS) vulnerabilities in a web application, I am curious if there are security measures equivalent to Content-Security-Policy: frame-ancestors and X-Frame-Options for JavaScript. My objective is to restrict the abilit ...

Thumbnail Option in the WordPress Media Uploader

Is it possible to add support for selecting image size (thumbnails) in the Media Library popup created using the wp.media() function in WordPress? I am currently using WordPress 4.5.2 and my code sample is as follows: wp.media.frames.selectFile=wp.media( ...

Tips for updating the value within a textfield in HTML

I am looking to dynamically update the value displayed in my Revenue textfield by subtracting the Cost of Goods from the Sales Price. I have included an image of the current layout for reference, but I want the Revenue field to reflect the updated value af ...

Exploring the effectiveness of testing Svelte components

Looking to test a component that utilizes a third-party module without mocking the imported components? Check out this example: // test.spec.ts import Component from "Component"; describe('Component', () => { test('shoul ...

form for submitting multiple data via Ajax

I am working with two forms (request and feedback) where I need to use jQuery Ajax to send the data. When a user submits a request, the subject line will display "Request". If they submit feedback, the subject line will display "Feedback". Here is my cur ...

Looking to extract data from JavaScript using Scrapy 1.4.0?

Apologies for my lack of proficiency in English. As a beginner in scrapy, I am seeking guidance on an issue I encountered while trying to scrape a particular website. Below is the code for my spider: import scrapy from bs4 import BeautifulSoup as bs clas ...

Issue: Unrecognized element type in next.js while starting development server

Every time I run npm run dev, I encounter the following error: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from th ...

When you tap on the screen, the keyboard disappears and you have to hold

I have encountered an issue in my web view where I am programmatically creating an input field element using JavaScript and setting focus to it after creation. The problem is that the keyboard pops up for a split second and then closes when trying to focus ...

What is the best way to filter out specific data fields from console.log in JavaScript?

When working with Java, I often use lombok to exclude certain fields from being printed. For instance, the @ToString.Exclude annotation can be used to prevent printing the user token. import lombok.ToString; public class TokenResponse { @ToString.Excl ...

CSS: Continuous animation loop does not smoothly transition between initial and final keyframes

It seems like I have come across an issue with a CSS animation that I can't find a solution for. The animation is supposed to loop infinitely, and while it is working, there is a problem. // CSS @keyframes myanim { 0% { transform: translate(0, 0) ...

Unable to access properties of an unknown item (reading 'remove')

Can you provide guidance on how to remove the top-level parent element of a div? I've been attempting to delete the main parent element of a specific div. element.innerHTML = ` <div class="postIt-item"> <div class="postIt-item-btn ...

Slate Map by Google Navigation

I have a situation here that is similar to the grey maps, except all the buttons are visible. Everything appears normal except for the Map tiles, which are all grey! It's strange because it loads nicely at zoom level 8 and then zooms in to the maximum ...