Alter the button's color seamlessly while staying on the same page

I have implemented a feature that allows me to change the category of photos without having to leave the page and it works perfectly.

My next goal is to create a button system where the pre-defined category of a photo is indicated by a button with a green background, while the other two categories have buttons with red backgrounds. When a user selects a different category, I want the corresponding button to turn green and the others to stay red. The green css class is c_on and the red css class is c_off.

How can I use JavaScript/ajax/jquery to set the right css class for each button?

I would appreciate any help. (Please note that the styles are correctly defined in my code, but I couldn't paste them here properly so I used a comment).

JS:

<script type="text/javascript">
$(function () {
$('form').on('submit', function (e) {
    $.ajax({
        type: 'post',
        url: "test_ajax_update_code.php",
        data: $(this).serialize(),
        });
    e.preventDefault();
    });
});
</script>

CSS:

.c_on {color: #000;background-color:#F00;}
.c_off {color: #000;background-color:#0F0;}

HTML:

<img src="myfoto1.jpg" width="500" height="333" border="0"><br>
            <form id="form1">
            <input name="num" type="hidden" value="1373" >
            <input name="shw" type="hidden" value="1" >
            <input type="submit" value="1" class="c_on">
            </form>
            &nbsp;&nbsp;&nbsp;
            <form id="form2">
            <input name="num" type="hidden" value="1373" >
            <input name="shw" type="hidden" value="2" >
            <input type="submit" value="2" class="c_off">
            </form>
            &nbsp;&nbsp;&nbsp;
            <form id="form3">
            <input name="num" type="hidden" value="1373" >
            <input name="shw" type="hidden" value="3" >
            <input type="submit" value="3" class="c_off">
            </form>
        <img src="myfoto2.jpg" width="500" height="333" border="0"><br>
            <form id="form1">
            <input name="num" type="hidden" value="1374" >
            <input name="shw" type="hidden" value="1" >
            <input type="submit" value="1" class="c_off">
            </form>
            &nbsp;&nbsp;&nbsp;
            <form id="form2">
            <input name="num" type="hidden" value="1374" >
            <input name="shw" type="hidden" value="2" >
            <input type="submit" value="2" class="c_on">
            </form>
            &nbsp;&nbsp;&nbsp;
            <form id="form3">
            <input name="num" type="hidden" value="1374" >
            <input name="shw" type="hidden" value="3" >
            <input type="submit" value="3" class="c_off">
            </form>

Answer №1

If you want to achieve this, you can follow these steps:

// Change all buttons to c_off state
$('input[type="submit"]').removeClass('c_on').addClass('c_off');

// Change the submitted button to c_on state
$(this).find('input[type="submit"]').removeClass('c_off').addClass('c_on');

With these changes, your code will appear like this:

$(function () {
    $('form').on('submit', function (e) {
        $.ajax({
            type: 'post',
            url: "test_ajax_update_code.php",
            data: $(this).serialize(),
        });

        // Change all buttons to c_off state
        $('input[type="submit"]').removeClass('c_on').addClass('c_off');

        // Change the submitted button to c_on state
        $(this).find('input[type="submit"]').removeClass('c_off').addClass('c_on');

        e.preventDefault();
    });
});

Answer №2

Understanding your point is a bit challenging, but by incorporating a couple of events and booleans, you should be able to accomplish something similar to this quite easily.

var flag_1 = false;

if (flag_1 === true) {
    //modify button styles
}

var element = getElement('div.image'); // just an example

element.addEventListener('click', function () {
    flag_1 = true;
}

And there wouldn't even be a need for ajax. For instance, you could submit when all flags are set to true.

Answer №3

Hopefully this information proves to be beneficial

$('input:submit').on('click',function(){
   $('input:submit').removeClass('c_on').addClass('c_off');
   $(this).removeClass('c_off').addClass('c_on');
})

Answer №4

To implement functionality for toggling classes on buttons, you need to add a click event listener to each button. This event listener will remove the .c_on class from any button and apply it to the clicked button.

$('button').on('click', function () {
    $('.c_on').removeClass('c_on').addClass('c_off');
    $(this).removeClass('c_off').addClass('c_on');
});

Answer №5

Give this approach a try and inspect the CSS for the appropriate color for the class.

UPDATE:

  1. The id attribute must be unique. Therefore, I have updated the id of the forms to be represented by a class instead.
  2. Additionally, I have included a new data-image property to distinguish between the different sets of buttons.

Revised Code snippets:

$(function() {
  $('form').on('click', 'input[type="submit"]', function(e) {
    $.ajax({
      type: 'post',
      url: "test_ajax_update_code.php",
      data: $(this).parent().serialize(),
    });
    var clicked = $(this),
      imageName = clicked.data("image");
    clicked.removeClass("c_off").addClass("c_on");
    $('input[type="submit"]').each(function() {
      var self = $(this);
      if (!clicked.is(self)) {
        if (self.hasClass("c_on") && imageName == self.data("image"))
          self.removeClass("c_on").addClass("c_off");
      }
    });
    e.preventDefault();
  });
});
.c_off {
  color: #000;
  background-color: #F00;
}
.c_on {
  color: #000;
  background-color: #0F0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<img src="myfoto1.jpg" width="500" height="333" border="0">
<br>
<form class="form1">
  <input name="num" type="hidden" value="1373">
  <input name="shw" type="hidden" value="1">
  <input type="submit" value="1" class="c_on" data-image="img1">
</form>
&nbsp;&nbsp;&nbsp;
<form class="form2">
  <input name="num" type="hidden" value="1373">
  <input name="shw" type="hidden" value="2">
  <input type="submit" value="2" class="c_off" data-image="img1">
</form>
&nbsp;&nbsp;&nbsp;
<form class="form3">
  <input name="num" type="hidden" value="1373">
  <input name="shw" type="hidden" value="3">
  <input type="submit" value="3" class="c_off" data-image="img1">
</form>
<img src="myfoto2.jpg" width="500" height="333" border="0">
<br>
<form class="form1">
  <input name="num" type="hidden" value="1374">
  <input name="shw" type="hidden" value="1">
  <input type="submit" value="1" class="c_off" data-image="img2">
</form>
&nbsp;&nbsp;&nbsp;
<form class="form2">
  <input name="num" type="hidden" value="1374">
  <input name="shw" type="hidden" value="2">
  <input type="submit" value="2" class="c_on" data-image="img2">
</form>
&nbsp;&nbsp;&nbsp;
<form class="form3">
  <input name="num" type="hidden" value="1374">
  <input name="shw" type="hidden" value="3">
  <input type="submit" value="3" class="c_off" data-image="img2">
</form>

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

Post request sent from jQuery to Node.js using the POST method

I can't seem to figure out what's going wrong, as my AJAX call using jQuery isn't passing values to my Node Express App. The console log output is showing "{}" Interestingly, when I tried using curl, it worked perfectly fine unlike the jQue ...

Preventing CSS shapes from overlapping with the next DIV

I'm currently working on creating a V-shape using CSS. While I have successfully created the shape, I am facing an issue where I cannot get the shape to appear "above" another div with a background image when it is placed before it and made negative. ...

Safari causing issues with AJAX requests when using HTTPS

While I'm not an expert in ajax, the request I have is quite simple: $.ajax({ url: "https://62.72.93.18/index.php?a=get_lights", dataType: 'jsonp', success: function (res) { notify ? jsonLightsDone(re ...

The placement of text appears to be incorrect when applying the float:left property in CSS

My issue is that I want #text1 to display on the right side of #video1, and #text2 to be positioned next to #video2. However, currently #text2 is also appearing beside #video1. Can someone please explain why this is happening and provide a solution to fi ...

Accessing the camera or photo library in React Native does not require any permissions

In my current project, I am developing an app that requires users to upload images from their photo library or camera. To access the camera functionality, I am utilizing the react-native-image-picker library without integrating react-native-permissions. ...

css center arrow-aligned underline text

Trying to emphasize my text with an additional arrow centered on the line is proving to be a challenge. When attempting this, the text does not align in the center of the page. .souligne { line-height: 17px; padding-bottom: 15px; text-transform: u ...

Edit data with modal form in Angular-UI

Currently in the process of developing a single page todo application using AngularJs and Angular-Ui. Encountering difficulties when attempting to edit a todo item at this stage. The plan is to utilize a modal window for editing information, successfully ...

Instantaneous data refresh using Firebase Cloud Functions

Currently, I am working on developing a chat feature in React using Firebase cloud functions. However, I am facing an issue where I do not receive updates when a user sends a message. Below is the code snippet that I have been working with: const app = a ...

When I hover over my divs, my span is positioned behind them

Greetings, I apologize for any language barriers. I will do my best to articulate my issue clearly. I have experimented with various approaches and reviewed similar questions, but unfortunately, I am unable to resolve the problem... I have created a title ...

JavaScript: A guide to solving systems of equations

I'm attempting to perform algebraic operations in JavaScript using certain conditions and known variables. However, I lack proficiency in mathematics as well as JavaScript to comprehend how to articulate it. Here are the conditions: var w1 = h1/1.98 ...

Troubleshooting problem with jQuery UI accordion and sortable feature

I've run into an issue with the sortable functionality of accordion. I am attempting to drag and reorder the <h3> elements, but for some reason, the sorting is not functioning as expected. I followed the instructions from the official demo (here ...

jQuery experiences compatibility issues with IE7, IE8, and IE9 while functioning smoothly on other web browsers

An issue has been encountered with this query in IE7, prompting an error message stating "Object Expected". While in IE8/9 there is no error but the query does not function properly. However, it works fine in all other modern browsers. If (jQuery("#tabs ...

Retrieving data from NodeJS ExpressJS variables

Hey fellow developers, Currently, I'm working with Express and Ajax to transfer data from the client to NodeJS. I am struggling with a situation where my variable seems to be undefined outside of the function. I would really appreciate it if someone ...

I'm curious about using NextJS to fetch an API with a specific router ID. Can anyone provide guidance on how to achieve this and then render the data as HTML?

Greetings! I am currently coding in NextJS and working on a user page that fetches user-specific information from an API. My goal is to extract the ID query from the URL and use it to make an API request. The API endpoint follows this structure: /Users/{i ...

What is the most effective method for retrieving Key-Value Pairs from a disorganized String?

Avoiding hard-coded rules specific to certain patterns is crucial. I am currently working on a project similar to AWS Textract (link here). I have successfully extracted data from files, albeit in an unstructured manner. Now, my goal is to find the best w ...

Identifying whether a webpage has integrated Google Analytics

I am working with a node server. I provide a Url in the request and utilize cherio to extract the contents. My current goal is to identify whether the webpage uses Google Analytics. How can I achieve this? request({uri: URL}, function(error, response, bod ...

Ignoring the partial view's click action

Within my parent view, there is a partial view containing two pseudo buttons: thumb up and thumb down, along with a paragraph containing assigned classes. Despite setting up two functions to execute when 'ready', the partial view does not respon ...

Alter appearance using various classes

I am seeking assistance in changing the font of text using classes. I have multiple texts with different classes and I want to be able to edit all the texts without adding another dropdown menu. I believe that the change needs to occur in a script. Pleas ...

The Javascript Image() function fails to load or render

I am currently in the process of developing a basic Sprite class for implementation in a canvas game. However, I am encountering an issue where the image specified during the creation of a new instance of the class does not trigger the onload or onerror ev ...

Ways to move upward from a lower position

I am trying to create a hover effect where the title and content move to the right position upon hovering. The issue I am facing is that the transition on the `Title` class is not working, and as a result, the hover effect is also not functioning properly ...