Determine the Javascript code needed to identify the button change that was implemented

As a beginner in the world of Javascript, I've been experimenting with incorporating Javascript into my ASP.NET MVC project.

Within my project, I have multiple buttons that toggle between different states, such as from ON to OFF. Each button corresponds to a specific record, and I am trying to determine which state change each button triggers - whether it becomes OFF or ON.

Currently, I've been using an if statement to check the toggleClass method, but I suspect this may not be the most effective approach as it doesn't always yield the desired outcome.

Below is an example snippet of my code:

<a id="menu-toggle_@j" href="#" class="btn btn-xs"><i class="glyphicon glyphicon-chevron-up"></i></a>
<script>
    $('#menu-toggle_@j').click(function () {
         $(this).find('i').toggleClass('glyphicon glyphicon-chevron-up').toggleClass('glyphicon glyphicon-down');
             $(if('#menu-toggle_@j').toggleClass('glyphicon glyphicon-down')){

I would greatly appreciate any guidance or assistance with this issue.

Answer №1

If you want to check the status of a button based on its class, you can easily do so using $.hasClass():

$('button').click(toggleBtn);
$('#getEveryStatus').click(getEveryStatus);

function toggleBtn(){
    $(this).toggleClass('on');
    
    if($(this).hasClass('on')){
        $(this).next('.status')
               .text('The button above is now ON.');
    } else {
        $(this).next('.status')
               .text('The button above is now OFF.');
    }
}

function getEveryStatus(){
    var list = '';
    $('button').each(function(i){
    list += 'Button #' + i + ' is ' + ($(this).hasClass('on')? 'ON':'OFF') + '.\n';
    });
    
    alert(list);
}
button{
    width: 4em;
    height: 2em;
    border-radius: 2em;
    border: none;
    outline: none;
    position: relative;
    background: #ddd;
    cursor: pointer;
    -webkit-transition: background .2s ease;
    transition: background .2s ease;
}

button.on{
    background: #63e63e;
}

button:before{
    content: '';
    position: absolute;
    top: 50%;
    left: 3em;
    height: 2em;
    width: 2em;
    margin-top: -1em;
    margin-left: -1em;
    background: #fff;
    border-radius: 2em;
    box-shadow: 0 0 5px rgba(0,0,0,.5);
    -webkit-transition: left .2s ease;
    transition: left .2s ease;
}
button.on:before{
    left: 1em;
}

#getEveryStatus{
    color: blue;
    text-decoration: underline;
    cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<button></button>
<p class="status">The button above is now OFF.</p>

<button></button>
<p class="status">The button above is now OFF.</p>

<p id="getEveryStatus">Click here to get every status</p>

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 box shadow feature seems to be malfunctioning on Android devices

It seems that the box shadow is not functioning properly on Android devices, without any clear explanation as to why. My attempt to address this issue included the following code: -webkit-box-shadow: inset 0 0 0 2px #F3D280; box-shadow: inset 0 0 0 2px # ...

The Panel DefaultButton malfunctions when the Textbox is expanded by the AJAX Toolkit AutoComplete feature

I'm having trouble setting the default button for certain controls like TextBox using ASP.NET Panel because it doesn't seem to work properly with the AJAX Control Toolkit's AutoCompleteExtender. Can someone please assist me with this issue? ...

Hidden visibility of input field prevents the value from being posted

I have a dropdown menu containing numbers as options. When a user selects a number, I want to display an input box using jQuery based on their selection. However, the issue arises when I try to submit the values of these input boxes as they are not being s ...

Node.js server continues running after attempting to stop with ctrl + C following starting the server using the command "npm start"

Whenever I initiate my server by typing node app.js in the command line on Git Bash, I can stop it simply by using ctrl + C. In my package.json file, I have configured a start script that allows me to use the command npm start to kickstart the server: "s ...

I am encountering difficulties with generating images on canvas within an Angular environment

I am trying to crop a part of a video that is being played after the user clicks on it. However, I am encountering the following error: ERROR DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may no ...

Organize WordPress loop posts based on tags in real-time

I have integrated a custom loop into my WordPress custom blog page to display all my posts. Here's how I did it: <section class="container blog-article-actu"> <div class="row"> <?php $the_query = ne ...

Tips for troubleshooting PHP errors while making a jQuery AJAX request

My dilemma involves an HTML form that I submit to a PHP server. When I submit the form using a standard method with a submit button and the action set to "screen_custom.php", everything works perfectly fine. I receive a page filled with valid JSON data. H ...

Is there a way to customize the primary column in Material-table?

I am utilizing the Material-table and I am in need of rearranging the column index to be at the end of the table as the default position for this column (actions) is at the beginning. Here is the code snippet for the table: <MaterialTable title=" ...

The TypeScript compiler is indicating that the Observable HttpEvent cannot be assigned to the type Observable

Utilizing REST API in my angular application requires me to create a service class in typescript. The goal is to dynamically switch between different url endpoints and pass specific headers based on the selected environment. For instance: if the environmen ...

What could be causing my component to not update after I modify the states?

When I make an ajax request and update the state with the response data, my list of items does not rerender as expected. Even though the state is updated successfully, the changes are not reflected in the UI. export class Tiles extends React.Component { ...

The `<Outlet/>` from react-router is being rendered in a location outside of its intended wrapper div

Utilizing MUI for crafting a straightforward dashboard featuring an <AppBar>, a side <Drawer>, my component appears as follows: <> <AppBar> // code omitted <AppBar/> <Drawer> // code omitted <Drawer/> / ...

I'm looking for a creative JavaScript prototype example that can help illustrate the concept of prototypes. Can someone share an interesting sample with me

I've been trying to wrap my head around prototypes, but I just can't seem to grasp their purpose and function. Is there anyone who can provide a straightforward example (such as a collegeStudent object) that will clarify the fundamentals of proto ...

Should I use a single directive with ng-if statements in AngularJS, or opt for two separate directives?

Question about optimizing performance in Angular JS. I am using ng-repeat to display a list of search results. Each search item is extracted using a directive/template. Should I wrap two directives with ng-if statements or use one directive with multiple ...

Hapi/Node.js Reference Error for Request: Troubleshooting the Issue

I am facing an issue with my two API handlers: module.exports.loginWeb = function (request, reply, next) { if (request.auth.isAuthenticated) { return reply.redirect('/'); } if(request.method === 'get'){ rep ...

Leveraging the power of ReactJS alongside Google Tag Manager

Looking for a way to track my application using Google Tag Manager, I stumbled upon a popular package at https://www.npmjs.com/package/react-google-tag-manager. However, despite following the instructions, I am having trouble configuring it properly! Foll ...

guide on updating JQuery string with JavaScript to incorporate new parameters

Similar Question: How to replace only one parameter or fast with Jquery on Jquery String The website has a query string as follows: http://www.nonloso.html/?nome1=pollo&cognome1=chicken&nome2=a&cognome2=b&nome3=c&cognome3=d This ...

Having trouble with publishing to npm as public with the --access flag not functioning properly?

When trying to publish a fresh scoped package on NPM using the command npm publish --access public, I encountered the following error: ole@mki:~/cli$ npm publish --access public npm ERR! publish Failed PUT 403 npm ERR! code E403 npm ERR! F ...

Understanding the difference between the local and global locations of a three.js Object3D

Initially, I envisioned my small 'ship' with turrets that could track a target. This is the jfiddle I created to showcase it. You can view it here. However, when the turrets track, they behave strangely. I noticed that the turret seems to believe ...

The JavaScript code that functions properly in Codepen is not functioning on my HTML page

Can you help me understand why this code is working fine in CodePen, but not on my HTML page? I'm unable to identify the error that may have occurred. Any assistance would be greatly appreciated! I suspect there's an issue with connecting some jQ ...

When the icon is clicked, initialize the jQuery UI Datepicker

Here is the code I am working with in a Backbone view: <input type="text" id="fromDate" name="fromDate"/><a id="cal"> <img src="img/calendar.gif"></a> Within the view's JavaScript file, I have implemented the following: defi ...