Controlling the Class Attribute in a <td> Element with JavaScript Upon Click Event

I am currently grappling with a situation involving a table with 5 <td> elements. By default, these <td> are red in color. If the user clicks on one of them for the first time, it changes to blue. Subsequent clicks turn it orange and then back to red, repeating this cycle.

My goal is to prevent the user from selecting a new <td> if any other element already has a blue or orange color. In such cases, an alert should inform the user to "Un-select your previous choice" before allowing them to proceed. The previously selected <td> would revert to red upon selection of a new one.

Below is a snippet of my code:

$(".OpnSeat").on('click', function(e) {
  if ($(this).attr("class") == "OpnSeat seat_td") {
    $(this).addClass('openM seat_td');
  } else if ($(this).attr("class") == "OpnSeat seat_td openM") {
    $(this).removeClass('openM seat_td');
    $(this).addClass('openF seat_td');
  } else if ($(this).attr("class") == "OpnSeat openF seat_td") {
    $(this).removeClass('openM seat_td openM');
    $(this).removeClass('openF seat_td openM');
    $(this).addClass('OpnSeat seat_td');
  }
});
.seat_td {
  width: 60px;
  margin-right: 10px
}

.OpnSeat {
  color: red;
  border: 2px solid red;
}

.openM {
  color: blue;
  border: 2px solid blue;
}

.openF {
  color: orange;
  border: 2px solid orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="OpnSeat seat_td">
      <p class="intxt">1</p>
    </td>
    <td class="OpnSeat seat_td">
      <p class="intxt">2</p>
    </td>
    <td class="OpnSeat seat_td">
      <p class="intxt">3</p>
    </td>
    <td class="OpnSeat seat_td">
      <p class="intxt">4</p>
    </td>
    <td class="OpnSeat seat_td">
      <p class="intxt">5</p>
    </td>
  </tr>

</table>

FOLLOW THIS LINK TO VIEW THE FUNCTIONING JSFIDDLE

Please excuse any language limitations in my explanation. Any suggestions or guidance on this matter would be greatly appreciated.

Answer №1

The most efficient approach is to utilize the hasClass method.

Below is a concise demonstration:

$(".OpnSeat").on('click', function (e) {
  if($(".OpnSeat").hasClass('openM') && !$(this).hasClass('openM')) {
    alert('not allowed');
  } else {
    if ($(this).attr("class") == "OpnSeat seat_td") {
      $(this).addClass('openM seat_td');
    } else if ($(this).attr("class") == "OpnSeat seat_td openM") {
      $(this).removeClass('openM seat_td');
      $(this).addClass('openF seat_td');
    } else if ($(this).attr("class") == "OpnSeat openF seat_td") {
      $(this).removeClass('openM seat_td openM');
      $(this).removeClass('openF seat_td openM');
      $(this).addClass('OpnSeat seat_td');
    }
  }
});
.seat_td {
  width:60px;
  margin-right:10px
}
.OpnSeat {
  color:red;
  border:2px solid red; 
}
.openM {
  color:blue;
  border:2px solid blue; 
}
.openF{
  color:orange;
  border:2px solid orange; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
  <td class="OpnSeat seat_td"><p class="intxt">1</p></td>
  <td class="OpnSeat seat_td"><p class="intxt">2</p></td>
  <td class="OpnSeat seat_td"><p class="intxt">3</p></td>
  <td class="OpnSeat seat_td"><p class="intxt">4</p></td>
  <td class="OpnSeat seat_td"><p class="intxt">5</p></td>
</tr>

</table>

Answer №2

Feel free to use the code snippet provided below:

https://example.com/codesnippet

$(".ClickElement").on('click', function(e) {
  if ($(this).hasClass("ClickElement")) {
    // Perform necessary checks
    // Check for certain conditions before proceeding
    if ($(".customClassA").not(this).length > 0 || $(".customClassB").not(this).length > 0) {
      alert("Action not allowed, please deselect previous selection");
      return;
    }
  }

  if ($(this).attr("class") == "ClickElement customClass1") {
    $(this).addClass('activeClass1 customClass2');
  } else if ($(this).attr("class") == "ClickElement customClass1 activeClass1") {
    $(this).removeClass('activeClass1 customClass2');
    $(this).addClass('activeClass2 customClass2');
  } else if ($(this).attr("class") == "ClickElement activeClass2 customClass2") {
    $(this).removeClass('activeClass1 customClass2 activeClass1');
    $(this).removeClass('activeClass2 customClass2 activeClass1');
    $(this).addClass('ClickElement customClass1');
  }

});

Answer №3

To ensure that a different row from this one does not have orange or blue color, use the hasClass and not functions:

if($(".OpnSeat").not($(this)).hasClass("openF") || $(".OpnSeat").not($(this)).hasClass("openM") ) { 
      alert("not allowed !");
      return;
    }

Here is a functional example:

$(document).ready(function(){
  $(".OpnSeat").on('click', function (e) {
    if($(".OpnSeat").not($(this)).hasClass("openF") || $(".OpnSeat").not($(this)).hasClass("openM")) { 
      alert("not allowed !");
      return;
    }
    if ($(this).attr("class") == "OpnSeat seat_td") {
      $(this).addClass('openM seat_td');
    } else if ($(this).attr("class") == "OpnSeat seat_td openM") {
      $(this).removeClass('openM seat_td');
      $(this).addClass('openF seat_td');
    } else if ($(this).attr("class") == "OpnSeat openF seat_td") {
      $(this).removeClass('openM seat_td openM');
      $(this).removeClass('openF seat_td openM');
      $(this).addClass('OpnSeat seat_td');
    }

  });
});
.seat_td {
  width:60px;
  margin-right:10px
}
.OpnSeat {
  color:red;
  border:2px solid red; 
}
.openM {
  color:blue;
  border:2px solid blue; 
}
.openF{
  color:orange;
  border:2px solid orange; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
  <td class="OpnSeat seat_td"><p class="intxt">1</p></td>
  <td class="OpnSeat seat_td"><p class="intxt">2</p></td>
  <td class="OpnSeat seat_td"><p class="intxt">3</p></td>
  <td class="OpnSeat seat_td"><p class="intxt">4</p></td>
  <td class="OpnSeat seat_td"><p class="intxt">5</p></td>
</tr>

</table>

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

Steps for adding an HTML string to a div element using Ajax

I am facing some major challenges with Ajax, especially when it comes to appending HTML code to a div. I am attempting to append this HTML string to <div id="content-loader"></div> PHP function getLogo(){ $logo = '<div class="bg- ...

What is the reason behind why modifying data in beforeCreated/created/beforeMount does not activate watch in VUE?

Why is it that modifying data in beforeCreated/created/beforeMount does not activate the watch function in Vue? <template> <div> <titi :namer="parentName"></titi> </div> </template> <script> export defaul ...

I continuously encounter "undefined" when attempting to retrieve collections

Despite my best efforts, I am unable to retrieve the data from the server using the snapshot docs. I have verified that the collection is named "creaciones" in lowercase. There is one document in the collection with existing data. I have double-checked fo ...

Is there a way to use Bootstrap4 flexbox to create responsive images?

I'm currently working on the "Top Categories" section of my website and I'm facing issues with making the image cards responsive. Despite using flexbox classes from Bootstrap 4, I am unable to achieve the desired responsiveness. Can anyone help m ...

arrange items based on their category into arrays

I have a JSON file that needs to be arranged based on three specific fields. Here is an example snippet of the JSON data: { "Racename": "10KM", "Category": 34, "Gender": "Male", "Work": "Google", "FullName": "Dave Happner", "Rank": 1, "Poni ...

Having trouble getting the JavaScript slider to animate

My code works perfectly in Codepen but when I try to implement it on my website, it shows as a static image. You can view the code here: https://codepen.io/anon/pen/zPMKpv I'm using the exact same code on my website located at: Does anyone have any ...

Obtain the complete path in Vue router by utilizing nested routes

After creating nested routes for Vue Router, I encountered a problem while using the routes to generate a navigation menu. Currently, I am using route.path in 'router-link :to=' which only gives me a part of the path. I want to include the absolu ...

Ways to bypass or replace the overflow:hidden property of the parent container even when unable to modify its CSS styling

I'm encountering an issue. I'm currently developing a widget to showcase certain elements on a webpage. I have created a fiddle, please take a look: .wrapper { width: 300px; display: block; position: relative; overflow: hidden; back ...

Verify whether an email is already registered in firestore authentication during the signup process using Angular

When a user signs up for our app, I want them to receive immediate feedback on whether the email they are attempting to sign up with already exists. Currently, the user has to submit the form before being notified if the email is taken or not. This desire ...

What is causing iframes to fail on some websites?

Recently, while I was experimenting with a jQuery tutorial, I encountered an issue where iframes were not working as expected. Surprisingly, only the iframes from w3schools seemed to work fine, leaving me confused about what could be causing the problem. & ...

What is the best way to display the contents of an array that contains another array within it?

I need help looping through this array and displaying the "roleName" value. I want to use the map method to iterate over it. { "userMenuDTO": { "menuId": "13", "menuName":"PruebaMenu900 ...

Trying to access properties of undefined

I am having trouble adding the form control class to my select statement. The issue arises when props become undefined. Here's the code snippet: const useStyles = makeStyles({ root: { width: "100%", maxWidth: 500 } }); const cl ...

What is the best way to stack divs within a parent div that has a height set to auto?

Looking to stack two divs on top of each other within a parent div to create a tab system for an applet. The challenge is that the parent div has auto height and the exact height of the child divs is unknown. Absolute positioning allows me to stack the div ...

Creating a Custom Class for a Custom Button in TinyMCE 4 Using addButton()

Is there a way to add a custom class to a custom button using the addButton() function in TinyMCE? Here is an example: editor.addButton('keywords', { text: 'Insert Keywords', class: 'MyCoolBtn', ...

Is the utilization of the React context API in NextJS 13 responsible for triggering a complete app re-render on the client side

When working with NextJS 13, I've learned that providers like those utilized in the React context API can only be displayed in client components. It's also been made clear to me that components within a client component are considered part of the ...

Form an object using elements of a string array

Trying to convert a string array into an object. The string array is as follows : let BaseArray = ['origin/develop', 'origin/master', 'toto/branch', 'tata/hello', 'tata/world']; I want the resulting obje ...

Implementing route navigation in two components using a click button

To display the content of the Quiz component with the path "/quiz" after clicking a button and fetching the component with the path "/" is my goal. Here is the code snippet from the App.jsx file: <Router> <Routes> <Route ...

The elements within the array are being refreshed accurately, however, a separate component is being removed

I have developed a component that has the ability to contain multiple Value components. Users can add as many values as they want, with the first value being mandatory and non-removable. When adding two new Value components, I provide input fields for name ...

Implementing Vuejs Array Push in Separate Components

I am attempting to extract data from an object and store it in an array using Vue. My goal is to have each value stored in a separate array every time I click on an item. Each click should push the todo into a different array. How can I achieve this separa ...

Issues with hidden overflow and height attributes not functioning correctly in Internet Explorer 9 when using the DOCTYPE HTML standards mode

I have a <div> with overflow:hidden and height:100% that adjusts the div contents to fit the window's height on Chrome and Safari. However, in IE9, the div does not respect the styles of overflow:hidden and height:100%, causing it to expand to ...