Modify the button's color when clicked and add it to an array with JavaScript

I am currently working on changing the color of buttons to indicate a selection. When a button is selected, its value is added to an array. If the same button is clicked again, it becomes unselected and its color reverts back to the original state, with its value removed from the array. I have a total of 40 buttons in my demo. You can view the demo through this JSFiddle snippet.

function ctrl($scope) {
$scope.tooth=[];
var count=0;
$scope.setTooth = function(event,code) {

    if($scope.tooth.indexOf(code) > -1){
        alert("hiii");
        $scope.styleO = "styleOne";
        $scope.tooth.splice($scope.tooth.indexOf(code), 1);
        //$scope.tooth.push();
    }else{
         $scope.tooth[count]=code;
         alert("hello");
        $scope.styleT = "styleTwo";     
    }    
}
$scope.setQuadrantsTeeth = function(quadarent){

}
}

Thank you in advance for your help.

Answer №1

It's up to you to handle the pushing and splicing of arrays. But when it comes to applying styles 1 and 2, why not try this approach?

        $("button").click(function(){
         if($(this).hasClass("styleOne")){
          $(this).removeClass("styleOne");
          $(this).addClass("styleTwo");
         } else if($(this).hasClass("styleTwo")) {
          $(this).removeClass("styleTwo");
         } else if(!($(this).hasClass("styleTwo") || $(this).hasClass("styleOne"))){
          $(this).addClass("styleOne");
         }
        });

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

Customize a web template using HTML5, JavaScript, and jQuery, then download it to your local device

I am currently working on developing a website that allows clients to set up certain settings, which can then be written to a file within my project's filesystem rather than their own. This file will then have some parts overwritten and must be saved ...

Discover the total number of characters that can be accommodated in a single row of a string

I need to split a string into an array based on the number of characters that can fit on each line. Each element in the array should contain only one line of text. I have managed to calculate the number of lines in the string, but I'm struggling to de ...

Can you explain the distinction between ' &:hover' and ' & :hover' pseudoclass selectors?

While styling a Material-UI Button, I encountered an unexpected behavior when adding hover effects. When using & :hover, only the inner span of the button was affected. However, when using &:hover, the desired style was achieved. What is the diff ...

Ensure that the Footer spans the entire width of the screen by using a container with fluid width, while

What is the best way to ensure that my Footer spans the full width of the browser window? Note: My website uses Bootstrap, with the Footer utilizing 'container-fluid' while the page content utilizes 'container'. Live link: HTML < ...

Finding the position of the latest item added to an array

If I add an element into an array in this way: $arr[] = 'something'; How can I determine the index of 'something'? Is there a different approach to adding an element to the array and finding its index? ...

What could be the reason for Selenium refusing to accept dynamic variables in this specific function?

What is the reason for the difference in behavior between these two code snippets? monday_div = driver.find_element(By.XPATH, '//*[@id="GXPMonday"]') And why does this one not work as expected? weekdays = ['Monday', 'Tue ...

I'm attempting to showcase an HTML file by using res.sendFile within the Express framework

As part of my workflow implementation, I have set up a scenario where upon user login, the credentials are sent via Ajax to an Express route for verification. If the user exists, the route responds with a message "authorised" triggering a second Ajax call ...

View content from an external file within an iframe

My goal is to showcase a text file within an iframe that updates automatically every second. To achieve this, I have created a simple function: function refresh() { $("#derek").attr('src', $("#derek").attr('src')); }; The automati ...

"Restricting the height of a DIV container based on the size

Struggling with CSS as I try to get my #wrapper DIV to adjust its size based on its contents. I've experimented with 100% height and min-height, but nothing seems to work. Could it be related to relative versus absolute positioning? Here's a snip ...

Assign a class while directing visitors away from a particular webpage

Can a div have a class added on page load, but only when redirected from a specific link or page? I currently have an <a href="marketing.php" id="openMyMaterialTab"><button class="secondaryAction">See all</button></a> link on my la ...

Steps for creating a basic JQuery function for dividing integers

My website constantly updates with real-time data from our PI server, refreshing every 10 seconds. I've been given the task to take two existing data points already on my page and calculate their division, then visualize the new result on a graph. Due ...

Moving object sideways in 100px intervals

I'm struggling to solve this issue. Currently, I have multiple div elements (each containing some content) that I need to drag and drop horizontally. However, I specifically want them to move in increments of 100px (meaning the left position should b ...

AngularJS making use of multiple checkboxes to filter data from a nested JSON structure

Hi everyone, I came across a helpful resource on implementing multiple checkboxes filters in AngularJS: angular js multiple checkbox with custom filters I am facing a similar issue but with a multilevel JSON structure. Here is an example of what I am deal ...

Classes aren't displaying properly for elements inside

Is there a way to display the header only in a small size using the col-sm-* class of the div inside a container? It seems like the col-sm-* class is not working correctly and not floating them properly. <link href="https://maxcdn.bootstrapcdn.com/b ...

The value assigned to a dynamically created array in a void function may not be the same when returned in the main() function

Having a bit of trouble with dynamic arrays in my C program. Everything was running smoothly until I was required to move the creation of the dynamic array into a separate void function. After doing so, the program continued to work fine until I needed to ...

Arrange JSON data in ascending order based on the dates, starting with the most recent date, by utilizing jquery

I'm in need of assistance on sorting a list of articles from an external json file based on their creation date. Can anyone provide guidance? Currently, I am fetching the data using AJAX and displaying only 6 results, but I'm facing difficulties ...

Easily toggle between various image source paths

In my current application, all HTML files have hardcoded relative image paths that point to a specific directory. For example: <img src="projectA/style/images/Preferences.png"/> Now, I am considering switching between two different project modes: & ...

How can I position text in the top right corner of a v-card's v-img component in Vuetify.js?

I am using Vuetify.js and I am trying to show a single word on the right side of an image within a v-card: <v-card> <v-img src="https://cdn.vuetifyjs.com/images/cards/desert.jpg" aspect-ratio="2.75"> <span class= ...

Substituting Hebrew characters for Mandaic characters within certain HTML tags can cause links to malfunction

What causes the JavaScript code provided to replace Mandaic characters with Hebrew characters on a webpage to also disable all links on the page? The code snippet is as shown below: function replaceMandaicCharacters() { const mandaicLetters = "&bsol ...

Determine the number of properties present in two arrays by comparing them

Looking to compare two arrays and determine the count of items in the master list. A sample master list could be: { name: 'Emily', age: 29 }, { name: 'Jack', age: 31 }, { name: 'Lily', age: 28 }, { name: 'Emily', a ...