Using jQuery to apply a CSS class to a chosen radio button

How can I dynamically add a CSS class to a radio button based on its selection?

$("input[type=radio][name=align]").on('change', function() {
  var radVal = $("input[type=radio][name=align]").val();
  if (radVal == 'center') {
    $(".tlt1").addClass('centerCssClass').change();
    $(".tlt1").removeClass('topCssClass').change();
  } else if (radVal == 'top') {
    $(".tlt1").addClass('topCssClass').change();
    $(".tlt1").removeClass('centerCssClass').change();
  }
});
.centerCssClass {
  background-color: blue;
}

.topCssClass {
  background-color: red;
}

.tlt1 {
  float: left;
  height: 300px;
  width: 300px;
  background-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="align" value="center">Center<br>
<input type="radio" name="align" value="top">Top<br>
<div class="tlt1"></div>

Answer №1

There are two issues that need to be addressed here. The first problem lies in the incorrect selector you are using to retrieve the value. Make sure to use the this reference to fetch the value from the radio button that was clicked.

Secondly, it is essential to enhance the specificity of the CSS classes so they can override the original background-color setting of .tlt1. Consider implementing the following changes:

var $tlt = $(".tlt1");

$("input[type=radio][name=align]").on('change', function() {
  var radVal = $(this).val();
  if (radVal == 'center') {
    $tlt.addClass('centerCssClass').removeClass('topCssClass');
  } else if (radVal == 'top') {
    $tlt.addClass('topCssClass').removeClass('centerCssClass')
  }
});
.tlt1 {
  float: left;
  height: 300px;
  width: 300px;
  background-color: orange;
}

.tlt1.centerCssClass {
  background-color: blue;
}

.tlt1.topCssClass {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="align" value="center">Center<br>
<input type="radio" name="align" value="top">Top<br>
<div class="tlt1"></div>

Additionally, triggering the change() event on the div elements is unnecessary and redundant.

Answer №2

To access the value of the selected radio button and update the CSS class, you can utilize the :checked selector in your code. Make sure to adjust the CSS class declaration to customize the background-color as needed.

$("input[type=radio][name=align]").on('change', function() {
  var radVal = $("input[type=radio][name=align]:checked").val();
  if (radVal == 'center') {
    $(".tlt1").addClass('centerCssClass').removeClass('topCssClass');
  } else if (radVal == 'top') {
    $(".tlt1").addClass('topCssClass').removeClass('centerCssClass');
  }
});
.tlt1.centerCssClass {
  background-color: blue;
}

.tlt1.topCssClass {
  background-color: red;
}

.tlt1 {
  float: left;
  height: 300px;
  width: 300px;
  background-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="radio" name="align" value="center">Center<br>
<input type="radio" name="align" value="top">Top<br>
<div class="tlt1">tlt1</div>

Answer №3

since the background color of tlt1 cannot be overridden

you must include !important after centerCssClass and topCssClass in the CSS

$("input[type=radio][name=align]").on('change', function() {
  var radVal = $(this).val();
  var tlt1 = $("#tlt1");
  if (radVal == 'center') {
    tlt1.addClass('centerCssClass').change();
    tlt1.removeClass('topCssClass').change();
  } else if (radVal == 'top') {
    tlt1.addClass('topCssClass').change();
    tlt1.removeClass('centerCssClass').change();
  }
});
.centerCssClass {
  background-color: blue !important;
}

.topCssClass {
  background-color: red !important;
}

.tlt1 {
  float: left;
  height: 300px;
  width: 300px;
  background-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="align" value="center">Center<br>
<input type="radio" name="align" value="top">Top<br>
<div id='tlt1' class="tlt1"></div>

Answer №4

give this a shot

consider using id rather than class tlt1

$("input[type=radio][name=align]").on('change', function() {
  var radVal = $(this).val();
  if (radVal == "center") {
    $("#tlt1").removeClass('topCssClass').change();
    $("#tlt1").addClass('centerCssClass').change();
    $("#tlt1").removeClass('tlt1');
  } else {
    $("#tlt1").removeClass('centerCssClass').change();
    $("#tlt1").addClass('topCssClass').change();
    $("#tlt1").removeClass('tlt1');
  }
});
.centerCssClass {
  float: left;
  height: 300px;
  width: 300px;
  background-color: blue;
}

.topCssClass {
  float: left;
  height: 300px;
  width: 300px;
  background-color: red;
}

.tlt1 {
  float: left;
  height: 300px;
  width: 300px;
  background-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="align" value="center">Center<br>
<input type="radio" name="align" value="top">Top<br>
<div class="tlt1" id="tlt1"></div>

Answer №5

Great job, your solution is accurate! Just remember to update the

var radVal = $("input[type=radio][name=align]").val();
inside the change event to var radVal = $(this).val();

Currently, you are fetching the value of the first element with input tag, having attributes type='radio' and name='align'. As a result, it always returns 'center' as the value. By using $(this), you target the specific element that was changed.

Furthermore, there’s no need to trigger the change() event on your .tlt1 element.

Lastly, in your CSS, lower values take precedence over higher ones. This explains why your background didn’t change - the styling for .tlt1 class had more significance than centerCssClass.

Check out this working example below:

$("input[type=radio][name=align]").on('change', function () {
    var radVal = $(this).val();
    if (radVal == 'center') {
        $(".tlt1").addClass('centerCssClass');
        $(".tlt1").removeClass('topCssClass');
    } else if (radVal == 'top') {
        $(".tlt1").addClass('topCssClass');
        $(".tlt1").removeClass('centerCssClass');
    }
});
.tlt1 {
  float: left;
  height: 300px;
  width: 300px;
  background-color: orange;
}

.centerCssClass {
  background-color: blue;
}

.topCssClass {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="align" value="center">Center<br>
<input type="radio" name="align" value="top">Top<br>
<div class="tlt1"></div>

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

Photo positioned on top of the form with Bootstrap 5

I am working on creating a responsive webpage using Bootstrap, where I need to display a large image above a form. To manage the size of the image, I have placed it inside a "peek-view" container which allows scrolling both horizontally and vertically to v ...

What is the most efficient method for retrieving all form elements that are currently visible using jQuery and do not belong to a particular class?

Currently, I am attempting to reassign a new tab-index within a provided form. In order to achieve this, I aim to exclude any form elements that are not visible (invisible) and also those with a specific class (".offscreen"). I have been using the followi ...

floating point for a list item compared to other elements

nav > ul > li { float: left; } #one { float: left; } <nav> <ul> <li> he has a cow </li> <li > he has a dog </li> <li> he has a mouse </li> </ul> & ...

Dropdown selection values were not set appropriately

I've been encountering an issue with setting the selected value in a drop-down list using the code below. The values are being split from a comma-separated string, but it's not functioning as intended. When I use string='text1,text2,text3,t ...

The CSS 'top' attribute is without impact

As I begin my journey with CSS, I am eager to grasp some of its behaviors. In the CSS file, the following code is defined: #spa { position : absolute; top : 8px; left : 8px; bottom : 8px; right : 8px; min-height : 500px; min-width : 500px ...

What is the best way to create a text input that is both secure and non-editable?

While I am aware of the <input type="text" readonly /> possibility, it is not entirely secure. For example, if there is an input field that must remain uneditable by users, making it "readonly" can still be bypassed by inspecting the code and remov ...

The functionality of the window.location.href in an Asp.Net MVC application is not properly functioning on Google Chrome

Hey there! I'm facing an issue with jQuery concerning window.location.href in my ASP.NET MVC application. Here's what's going on: I have a grid view that utilizes Html.actionlink to make an AJAX request which deletes a row from the database. ...

Handsontable: A guide on adding up row values

I have a dynamic number of columns fetched from the database, making it impossible to predict in advance. However, the number of rows remains constant. Here is an illustration: var data = [ ['', 'Tesla', 'Nissan', & ...

CORS - Preflight request response fails access control verification

I've been attempting to send a GET request to a server with the same domain as my local host, but I keep encountering the following error: The preflight request response fails the access control check: The requested resource does not have an ' ...

Center a grid of cards on the page while keeping them aligned to the left

I have a grid of cards that I need to align in the center of the page and left within the grid, adjusting responsively to different screen sizes. For example, if there are 10 cards and only 4 can fit on a row due to screen size constraints, the first two ...

Having issues with the presentation of full_numbers pagination in IE while using jQuery dataTables

I am currently utilizing the DataTables jQuery plugin (found at ) with the initialization code below: $('#reconcile_table').dataTable( { 'bSort' : true, 'bFilter' : true, 'bSortClasses' : false, &a ...

What methods can I use to transfer data from one domain to another domain utilizing Ajax JSONP?

Example: The URL of my site is "http://localhost:54887/CustomOrdering.html", but I want to retrieve data from another site "http://localhost:27746/Orders.aspx". In order to do this, I have implemented the following code in my CustomOrdering.html: function ...

Focusing on a specific image using Jquery

I am looking to specifically target the image within the "hero1project3" class, however, the image is currently set as a background. Is there a way in jQuery to apply effects like blur only to the image itself, for example, using ".hero1project3 img"? HTM ...

Launching JQuery modal upon button click

I'm encountering an issue with jQuery Mobile. Here is the JSFiddle link: http://jsfiddle.net/Gc7mR/3/ Initially, I have a Panel containing multiple buttons. The crucial button has an id of 'define'. <div data-role=header data-position= ...

Is there a way to arrange the cards in a row so they fill up the grid before moving on to the next row?

After retrieving data from a table in my database, I am displaying it on the screen as cards. However, the issue is that all the cards are displaying on the left side of the screen in a single column, rather than appearing in rows of 3 as desired. Below i ...

Passing parameters to a new page in AngularJS using ng-click event

At the top of my page, I have three buttons with an input box underneath. <div> <form> <div> Enter Show Name<input type="text" ng-model="showName" /> </div> </form> </div> ...

Building a new directory in Laravel

I am facing an issue with allowing users to create a folder in Laravel 4 through an ajax request that goes through the route and controller@method. I have tested the ajax success request to ensure it calls the right method. However, when I try to use mkdir ...

Challenges with handling Ajax responses in Ruby on Rails

I'm currently facing an issue with the Ajax response in my Rails application, and I'm unsure of how to troubleshoot it. Here is the code that is functioning correctly: View <div id="<%= dom_id(comment) %>_count"> <%= Like.wh ...

Converting an HTML ul-li structure into a JavaScript object: Steps to save the structure

My HTML structure uses ul and li elements as shown below: <ul class="treeview" id="productTree"> <li class="collapsable lastCollapsable"> <div class="hitarea collapsable-hitarea lastCollapsable-hitarea"></div> <span ...

Showing JSON data stored in Local Storage

My goal is to retrieve a JSON object from local storage in the web browser and then display the values. While I am able to save the JSON object and add new data to it, I am struggling with the logic required to fetch and show it. For context, the variable ...