Ensure that only one button can be selected at a time for non-radio button elements in the

This is the code snippet I am working with


$(document).ready(function(){
    $("a.btn1").click(function() {   
        $(this).find("i").toggleClass("fa-thumbs-o-up fa-thumbs-o-down");
    });
    
    $("a.btn2").click(function(){    
        $(this).find("i").toggleClass("fa-smile-o fa-frown-o"); 
    }); 
        
    $("a.btn3").click(function(){ 
        $(this).find("i").toggleClass("fa-unlock fa-unlock-alt"); 
    }); 
});
.fa {
    font-size: 58px !important;
}

My challenge now is to select only one button at a time without them functioning as Radio Buttons

I have tried various examples but most of them work like Radio buttons

What I need is to use these as anchor tags and allow only one option to be selected at a time

Currently, all three options are getting selected at once

This causes errors when submitting as the score values do not match up correctly

Answer №1

To enhance the functionality, you can incorporate the active-class and original-class attributes within the <a> tag. Retrieve these values using the .attr() method.

$(".col-sm-10>a").click(function() {
  var selected = $(this).find('i')[0];

  $(".col-sm-10>a>i").removeClass(function(e) {
    return selected !== this ? $(this).attr('active-class') : $(this).attr('original-class');
  }).addClass(function() {
    return selected !== this ? $(this).attr('original-class') : $(this).attr('active-class');
  });
});
.fa {
  font-size: 58px !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" />
<div class="col-sm-10 col-sm-offset-1">
  <a class="btn1"><i original-class='fa-thumbs-o-up' active-class='fa-thumbs-o-down' class="fa fa-thumbs-o-up"></i></a>
  <a class="btn2"><i original-class='fa-smile-o' active-class='fa-frown-o' class="fa fa-smile-o"></i></a>
  <a class="btn3"><i original-class='fa-unlock' active-class='fa-unlock-alt' class="fa fa-unlock"></i></a>
</div>

Answer №2

Updated answer with new information

-- ability to toggle selected answer

$('.buttons a').click(function() {
if ($(this).hasClass('selected')) {
    $(this).removeClass('selected');
    $('.buttons a i:nth-child(1)').removeClass('hidden').addClass('shown');
    $('.buttons a i:nth-child(2)').removeClass('shown').addClass('hidden');
  } else {
    $('.buttons a').removeClass('selected');
    $('.buttons a i:nth-child(1)').removeClass('hidden').addClass('shown');
    $('.buttons a i:nth-child(2)').removeClass('shown').addClass('hidden');
    $(this).addClass('selected');
          $(this).find('i').toggleClass('shown').toggleClass('hidden');
  }
})
.fa {
 font-size: 58px !important;
}
.selected i {
  color: red;
}
i.hidden {
  display: none;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="buttons col-sm-10 col-sm-offset-1">
  <a class="btn1">
    <i class="fa fa-thumbs-o-up shown"></i>
    <i class="fa fa-thumbs-o-down hidden"></i>
  </a>
  <a class="btn2">
    <i class="fa fa-smile-o shown"></i>
    <i class="fa fa-frown-o hidden"></i>
  </a>
  <a class="btn3">
    <i class="fa fa-unlock shown"></i>
    <i class="fa fa-unlock-alt hidden"></i>
  </a>
</div>

https://jsfiddle.net/Hastig/eno21p25/

Original style of response

-- unable to toggle selected answer

If you want to apply a class to the a tag for showing selection, you can remove 'selected' from all a tags and add it to this..

$('.buttons a').click(function() {
$('.buttons a').removeClass('selected');
  $('.buttons a i').removeClass('fa-thumbs-o-down fa-frown-o fa-unlock-alt');
  $('.buttons a.btn1 i').addClass('fa-thumbs-o-up');
  $('.buttons a.btn2 i').addClass('fa-smile-o');
  $('.buttons a.btn3 i').addClass('fa-unlock');
  $(this).addClass('selected');
if ($(this).hasClass('btn1')) {
    $(this).find("i").toggleClass("fa-thumbs-o-up fa-thumbs-o-down");
  } else if ($(this).hasClass('btn2')) {
    $(this).find("i").toggleClass("fa-smile-o fa-frown-o"); 
  } else if ($(this).hasClass('btn3')) {
    $(this).find("i").toggleClass("fa-unlock fa-unlock-alt"); 
  }
})
.fa {
 font-size: 58px !important;
}
.selected i {
  color: red;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="buttons col-sm-10 col-sm-offset-1">
  <a class="btn1"><i class="fa fa-thumbs-o-up"></i></a>
  <a class="btn2"><i class="fa fa-smile-o"></i></a>
  <a class="btn3"><i class="fa fa-unlock"></i></a>
</div>

https://jsfiddle.net/Hastig/hncLnzh4/

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

Scrolling horizontally in a container using the mouse wheel

Is there a way to enable horizontal scrolling in a div using the mouse wheel or drag functionality with jQuery? I attempted using draggable, but it did not work effectively in my specific code scenario. Currently, I have a horizontal scrollbar. Are there ...

The reason behind my unsuccessful attempt to utilize AJAX with the Google GeoChart API

Learning about JavaScript is exciting! I recently tried incorporating a Google Geochart to generate visual reports. The sample code looked like this: function drawRegionsMap() { var data = google.visualization.arrayToDataTable([ ['Country ...

Tips on achieving vertical movement within a div element from the bottom of the wrapper to the

I am struggling to animate a .alert div within its wrapper to fly up from the bottom of the wrapper by 40px. However, I am encountering difficulty as the alert div does not start at the bottom of the wrapper as intended. The desired behavior is for it to s ...

The class name remains unchanged despite the change in value

I am currently working on a webpage that features two interactive tabs. The goal is to have one tab highlighted as "active" while the other remains inactive when clicked, and then switch roles when the other tab is selected. Below is the code snippet I ha ...

Showcasing only one item at a time in AngularJS 1.x with ng-repeat; by clicking on "next", the subsequent item will be displayed,

Currently, I am working on a quiz web application that requires displaying a total of 100 questions across 3 different tabs - Math, GK, and English. The questions are filtered using an Angular filter. However, I'm facing an issue where each tab is sho ...

Is there a way to adjust the position of ::before elements without affecting the border placement?

I'm struggling with an element that has a CSS style ::before to display an arrow-up inside a black circle. Check out the code here The issue I'm facing is that the character \25b2 isn't centered vertically within the circle. Adjustin ...

The jsx file is not being parsed by Webpack

In my current project, I am working with a JSX file that contains React code. import React from 'react'; import {render} from 'react-dom'; class App extends React.Component { render () { return <p> Hello React!</p>; ...

Easily transform a CSS file for optimal use on dark backgrounds from scratch

I've got around 200 CSS files that look like this: /** * GeSHi Dynamically Generated Stylesheet * -------------------------------------- * Dynamically generated stylesheet for bnf * CSS class: , CSS id: * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 ...

Waveform rendering in HTML5 using wavesurfer.js struggles to handle large mp3 files

Recently, I was considering incorporating wavesurfer.js into one of my projects so I decided to explore the demo on To test it out, I uploaded a large mp3 file (approximately 2 hours long) onto the designated area in the middle of the page. It appeared to ...

javascript issues with ajax functionality

I am currently dealing with some JavaScript code that looks like this: alert(""); var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else {// code fo ...

transferring function from server to the client module named Next 13

After referencing the documentation for the app directory in Next.js, it is recommended to fetch data inside Server Components whenever feasible. Server Components always carry out data fetching on the server. This advice is particularly helpful for me as ...

JSON serialization fails due to cyclic structures causing an error

Looking at the data object structure displayed in the Safari console, here is what I see: _Api (2) 0 {company_code: 64, clerk_code: "RO", clerk_name: "Akshay", list_a: 1, list_b: 0} 1 {company_code: 64, clerk_code: "SA", clerk_name: "Lokur", list_a: 0, li ...

Exhibition of items arranged in a floating manner. I am looking to insert a new class within the layout using jquery

Let's dive into a bit more detail. I have a gallery with 9 elements aligned to the left, creating 3 elements per line as shown below: 1 2 3 <--line 1 4 5 6 <--line 2 7 8 9 <--line 3 What I am attempting to do is wh ...

Getting a variable from outside of the observable in Angular - a step-by-step guide

I have an Observable containing an array that I need to extract so I can combine it with another array. this.builderService.getCommercialData() .subscribe( data=>{ this.commercialDetails = data; this.commercialDetailsArr ...

React using Firebase: Receiving error "Cannot use import statement outside a module"

I've been following a helpful tutorial on setting up firebase authentication with React. However, I encountered some issues while trying to configure Firebase. I have created a firebase.js file as per the tutorial instructions: import firebase from &q ...

Obtain an array from an Ajax request using jQuery Datatables

I have integrated the jQuery DataTables Select plugin into my project to enable the selection of multiple rows from a table and storing their data inside an array. Subsequently, I am attempting to make an Ajax Request to pass this array to another PHP file ...

Unable to access image from JSON within Mobile Angular Ui utilizing Angular Js

Currently, I am able to retrieve various data from JSON such as Price and Display Order, but I am facing difficulty in fetching the image. HTML: <div ng-controller="chooseProductDescription"> <div ng-repeat="cat in productDescrip ...

Can you explain the purpose of the role attribute in XHTML? How is it commonly utilized?

After reviewing W3C's information about the role attribute, I am still unclear about its purpose. Is the role attribute meant to simply clarify the code, or do some browsers or spiders interpret it in a specific way? Could the role attribute serve as ...

Adding dynamic values to nested form groups in Angular Form Array

After following a tutorial on creating a reactive form in an Angular application, I managed to implement it successfully. However, I encountered an issue when trying to add an additional control called "setNumber" to the form array. I want this control to ...

Unable to eliminate border from image within label

The following code generates a border that appears to be approximately 1px thick and solid, colored grey around the image. Despite setting the border of the image to none, the border still remains. Here is the code snippet: <label> <img styl ...