How can I select a class for my HTML table once the button is clicked?

After clicking a button, I need to select between two classes (.Class1 and .Class2) declared in the css file StyleSheet1.css for my table tag. How can I achieve this?

<link href="Styles/StyleSheet1.css" rel="stylesheet" type="text/css" />
<table class="Class1">
    <tr>
        <td>Hello World!</td>
    </tr>
</table>

CSS File:

.Class1
{   
    background-color: Blue;
}
.Class2
{
    background-color: Red;
}

If possible, I would like to use C# to change classes dynamically, but if not, maybe JavaScript could work?

I'm fairly new to ASP and C#, with some experience in HTML.

Best Regards

Answer №1

If you're looking to add interactivity to your webpage, consider using a combination of Javascript and jQuery. Here is an example code snippet:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#btn1').click(function () {
                $('#tbl1').toggleClass('Class2');
            });
        });
    </script>
    <style>
        .Class1
        {
            background-color: Blue;
        }

        .Class2
        {
            background-color: Red;
        }
    </style>
</head>
<body>
    <table class="Class1" id="tbl1">
    <tr>
        <td>Hello World!</td>
    </tr>
</table>
    <button id="btn1">change</button>
</body>
</html>

Answer №2

For those utilizing asp.net webforms (not MVC) and looking to handle this task on the server side, you can convert the table into a control by including runat="server" and assigning an ID to it

<table class="Class1" id="myTable" runat="sever">
    <tr>
        <td>Hello World!</td>
    </tr>
</table>

After doing so, you will be able to manipulate the table server-side within the button click event or at any point in the page life cycle. Here is an example of how you could achieve this:

string cssClass = string.Empty;

if(/*Condition to determine if Class1 should be used*/)
{
     cssClass = "Class1";
}
else
{
     cssClass = "Class2";
}

myTable.Attributes["class"] = cssClass;

If you prefer a more concise approach, you could condense the code into one line like this:

myTable.Attributes["class"] = /*Condition to determin class 1*/ ? "Class1" : "Class2"; 

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

Optimizing Bootstrap 4 Flex-Row Dimensions

Issue: I'm currently working on a relatively intricate ListGroup using bootstrap v4. The .flex-row div is displaying some mysterious white space at the bottom, and I need assistance in eliminating it. Attempts Made So Far: I've experimented w ...

The scaling of the slick carousel image is not working as expected

Having an issue with the Slick carousel where images are not resizing based on browser size (original size is 300x228px). Just to clarify: When I shrink the browser window, the number of slides decreases but the images remain the same size. I've bee ...

Overlap of columns within a nested flexbox arrangement

While working with React and Styled Components, I encountered a problem of elements overlapping each other: https://i.stack.imgur.com/RuCYu.png There are a few instances of overlap, including: The padding below the <ul> element is colliding with ...

Achieving Vertical Alignment of Text and Icon in the Same Line Using HTML and CSS

I am struggling to align these icons vertically center with the text. However, there seems to be a slight offset of a few pixels. I have experimented with different solutions, but this is the closest I could get to. Can anyone explain why it's not ali ...

I'm perplexed by the inner workings of infinite ajax scroll in fetching additional posts

As someone who is new to JavaScript, I find it challenging to grasp the concept, especially when incorporating it with HTML. Despite this, I decided to experiment with infinite ajax scroll functionality. Below is my code snippet: var ias = jQuery.ias({ ...

When the nav-element is clicked, it will load the new content/file.php into the div with the id of "include."

Seeking the most efficient method to load content from a php file into a designated div on my webpage, prioritizing speed, minimal performance requirements, and ease of implementation. Unsure whether it's preferable to utilize php or javascript for t ...

Refreshing the electron renderer process is accomplished by executing an update query in sqlite3

Recently, I discovered that when I use an update query with knex in electron js, particularly with sqlite3, the renderer process automatically refreshes after the query is complete. Here's an example: index.html: ipc.send('UpdateTheRow', ...

A step-by-step guide on crafting a triangular-shaped div connected to another div

After working with HTML elements and trying to incorporate 2 divs, I realized that I couldn't achieve the triangle-shaped div that I actually needed. I have included an image for reference. Below is the HTML code snippet: <div style="background-c ...

Layered Architecture for ASP.NET/c# Website: A Structured Design Approach

In my ASP.NET website development, I have organized my code into layers such as form object classes, entity classes for business logic, controller classes to manage multiple entity classes, and data access classes. Each of the mentioned classes has its ow ...

Creating a variable before defining a function

Is there a way to define 'sender_psid' globally instead of inside the 'app.post' function so that it can be accessed by the function calls at the bottom? Note: Declaring it outside the function won't work due to 'webhook.even ...

Steps to extract key and value from a collection in Firebase database

In my Firebase database, I have a specific structure that I need to retrieve and display using ngFor in my view. However, I also need access to the unique key generated by Firebase when using the push method for each object. https://i.sstatic.net/nR2nK.pn ...

divs adjust their size based on how many are placed in a single row

I'm in the process of developing an online editing tool, and I'm interested to know if it's feasible to adjust the size of a <div> based on the number of visible div elements. For instance, I have a row with three columns, each set at ...

Issue with Chrome (2) preventing HTML5 video from loading using video.js

This particular question is identical to the one found at HTML5 video (video.js) not loading in Chrome, which unfortunately was left unresolved. When attempting to load only a mp4 source on Chrome, I encounter the following message in the console: Array[ ...

Eliminate unnecessary spaces in the input field located below the provided text

In the html code, I have an input field that looks like this: https://i.sstatic.net/DsD4y.png This is the CSS for the input fields: .form-control-1 { display: block; margin: 0 auto; width: 30%; height: 50px; padding: 6px 12px; font-size: 18p ...

Aggregate array based on specified criteria in ReactJS

Let's consider the following array data: array = [ { id: 1, count: 0.5 cost: 100 user: {id: 1, name: "John 1"}, type: {id: 1, name: "T1"}, period: {id: 1, name: "2021"} ...

Developing and modifying CSS within Flex3 Air

In the process of using the Flex 3 Air application, I am in need of generating a CSS file. It is crucial that I have the ability to both create and modify the CSS file, and also be able to reach specific styles by their respective class names. If you hav ...

Bootstrap 4 Alpha Grid does not support aligning two tables side by side

When working with Bootstrap 4, I am aware that the .col-xs classes have been removed. Instead of using .col, I have tested it on Bootstrap 3.5 which is currently being utilized. <div class="col-xs-4"> Table content for left ...

What is the syntax for creating a zip function in TypeScript?

If I am looking to create a zip function: function zip(arrays){ // assume more than 1 array is given and all arrays // share the same length const len = arrays[0].length; const toReturn = new Array(len); for (let i = 0; i < len; i+ ...

What is the process for assigning a class to every button on a webpage?

For a recent project, I utilized input[type="button"] to add a style to all of the buttons. Although it functions properly on most browsers, Internet Explorer 6 does not recognize the styling. Is there a workaround for this issue? Perhaps creating a speci ...

Exploring the Power of Title and the Wildcard Universal Selector in JavaScript CSS/HTML5

What is the method for adding a title to the div below? document.write('<div style="width:auto; margin:10px;"><table style="background-color:purple;" border="1" cellspacing="1" cellpadding="35">') The script in its entirety can be ...