Switching the border of a div that holds a radio button upon being selected

I have a piece of code that I use to select a radio button when clicking anywhere within a div, which represents a product photo. To make it clear for the customer, I want to add a border around the selected product. Here is the initial code:

<script type='text/javascript'>//<![CDATA[ 
$("div.div-check").on("click",function(event) {
    var target = $(event.target);
    if (target.is('input:radio')) return;
    var checkbox = $(this).find("input[type='radio']");

    if( !checkbox.prop("checked") ){
        checkbox.prop("checked",true);
       $('input:radio').filter(':checked').parent().addClass('checked');
    } else {
        checkbox.prop("checked",false);
    }
});
//]]>  

</script>

Also, I am concerned about the security vulnerability in my current code as it changes the checked status. Thank you for your help!

New: I believe I may have confused my original question and code with this specific part:

$('input:radio').filter(':checked').parent().addClass('checked');

This was just my attempt at adding a border effect using a CSS class named "checked". The solution suggested below involving .css might render this line unnecessary as the border would still show up without it.

However, I modified the code based on tchoow002's suggestion, but encountered an issue. When the user selects a different option after choosing one previously, the red border from the first choice remains even though the new one is selected. The correct value is returned, but the old selection retains the red border.

<script type='text/javascript'>//<![CDATA[ 
$("div.div-check").on("click",function(event) {
var target = $(event.target);
if (target.is('input:radio')) return;

var checkbox = $(this).find("input[type='radio']");

if( !checkbox.prop("checked") ){
checkbox.prop("checked",true);
$('input:radio').filter(':checked').parent().addClass('checked');
checkbox.parent().css("border","1px solid red");
} else {
checkbox.prop("checked",false);
checkbox.parent().css("border","none");
}
});
//]]>  
</script>

I attempted to incorporate the given code into the else statement, but it did not resolve the issue. Additionally, in the original code snippet,

$('input:radio').filter(':checked').parent().removeClass('checked');

Answer №1

Discover how to manipulate styles with .css()

Learn how to utilize .css() in order to retrieve the value of a style property for the initial element within the assortment of corresponding elements or to establish one or more CSS properties for each matched element.

If you wish to adjust the css property for the border of your checkbox's parent div, follow these steps:

To apply the border:

checkbox.parent().css("border","1px solid red")

To eliminate the border:

checkbox.parent().css("border","none")

Implement it like this:

if( !checkbox.prop("checked") ){
    checkbox.prop("checked",true);
    $('input:radio').filter(':checked').parent().addClass('checked');
    checkbox.parent().css("border","1px solid red");
    $('input:radio').not(':checked').parent().removeClass('checked').css("border", "none"); //Remove border and checked class from all other radios that are not checked
} else {
    checkbox.prop("checked",false);
    checkbox.parent().removeClass('checked'); //remove checked class when clicked twice
    checkbox.parent().css("border","none");
}

Alternatively,

Utilize .addClass to append an extra css class containing your desired border effect.

And use .removeClass to eliminate it as needed

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

How can you determine if a user has selected "Leave" from a JavaScript onbeforeunload dialog box?

I am currently working on an AngularJS application. Within this app, I have implemented code that prompts the user to confirm if they truly want to exit the application: window.addEventListener('beforeunload', function (e) { e.preventDefault ...

Learning to extract data with multiple parameters in Node.js

I am struggling to retrieve data that meets both parameter conditions. I want the data to be filtered by status and display search results, but currently it is showing all records without considering the status value: const customers = await Customer.fi ...

Why do I keep getting an ExpressionChangedAfterItHasBeenChecked error after trying to update a random color in an

Is there a way to assign a random color from an array without causing the error message: "ExpressionChangedAfterItHasBeenChecked"? Even though the color of the chip changes quickly before the message appears, it seems like it's working. How can I reso ...

What are the common practices for UI bindings in JavaScript and AJAX applications?

Background Information Currently, I am in the process of developing a traditional web application with most forms operating through AJAX. I am facing challenges in connecting the user interface to the model. As of now, I have to explicitly: Specify the ...

What is the best way to switch a boolean state in React using TypeScript?

Hey there! I'm diving into the world of React and TypeScript. My goal is to toggle a boolean state (true/false) using a handler function. While I've come across solutions in ES6, I'm struggling to grasp how it can be implemented in TypeScri ...

Manipulating HTML output with JavaScript

I am in the process of creating a website that retrieves and displays data from a mySQL database using PHP. When I toggle a switch, I want the displayed data to be refreshed with a new search query. Below is the Javascript function for the switch: functi ...

How is it possible that TypeScript does not provide a warning when a function is called with a different number of arguments than what is expected?

I am working on a vanilla JavaScript project in VS Code and have set up jsconfig.json. Here is an example of the code I am using: /** * @param {(arg: string) => void} nestedFunction */ function myFunction(nestedFunction) { // Some logic here } myFu ...

When the onLeave event of fullPage.js is activated

I am struggling to implement two CSS events when transitioning between sections on a fullPage.js application. To see my current progress, you can view the following fiddle: http://jsfiddle.net/pingo_/67oe1jvn/2/ My objectives are as follows: To modify t ...

Using jQuery UI to trigger Highlight/Error animations

Apologies if this question seems obvious, but I can't seem to find a clear answer anywhere... Is there a way to add a highlight/error message similar to the ones on the bottom right of this page: http://jqueryui.com/themeroller/ by simply using a jQu ...

Get rid of the underlined anchors in your email signature

I'm currently in the process of creating personalized email signatures for one of my clients. At this point, I am testing them on various platforms such as GMail, Hotmail, Brinkster, and more. One issue I am facing is trying to remove the underline t ...

The Safari browser restricts interaction with password inputs but allows interaction with other types of input fields

My password input field is styled like this: <input class="genericButton" id="login-password" type="password" name ="password" placeholder="Password"> While everything functions correctly in Chrome, I encounter an issue with Safari. When I try to i ...

Inserting additional information and assigning a category following a prosperous AJAX request accompanied by output from php echo

I'm currently working on implementing an AJAX call to my PHP file to send an email once a contact form is submitted. Initially, I had everything functioning properly where the response from PHP was displayed in a div above the form. However, I wanted ...

Converting MS Access databases

My latest project involves the conversion of an existing MS Access 2007 application into a web-based application. Currently, all data is stored in a SQL Server 2005 database. Given my limited web development experience, I am approaching this task with caut ...

Error: The function 'nivoSlider' is not defined for the object [object Object]

Trying to integrate a nivo slider into my WordPress website, but encountering a strange exception: Uncaught TypeError: Object [object Object] has no method 'nivoSlider' The website URL is: (It's in Hebrew, so you may not understand) - th ...

Debugging Typescript code with line numbers

When opening the console in a browser, typically the javascript line number of a function call or error message is displayed. However, my current setup involves using TypeScript, which gets compiled to Javascript. I am wondering if there is a way to retr ...

Start by declaring a scope variable using AngularJS

My go-to method for retrieving data from the server and displaying it on various components like tables or charts is by using ng-init="controllerFunction()". This function needs to be called every time the page loads. While ng-init gets the job done, I ca ...

Store the value returned by the function(data) from the $.post method in a variable

Hello Fellow Developers! I'm currently working on a coding project with the following objective: My goal is to extract URLs of files stored in a specific folder and then store them in an array using JavaScript. Here's how I envision the proces ...

The echo statement is failing to show any value following the ajax request

I am in need of assistance. I would like to output the value from a PHP echo statement using an AJAX call. Currently, the code is functioning without any errors. When I select options from a dropdown menu, the value is displayed on the console by using con ...

Customize the React Material UI Autocomplete with a unique dropdown menu and a convenient Add Button feature located at

Seeking assistance in creating an autocomplete feature in React using Material-ui, with a unique custom dropdown design including a button labeled Add New Element positioned at the bottom. Various attempts have been made to implement this feature, but enc ...

Update various components within a container

I have incorporated a function that automatically loads and refreshes content within a div every 10 seconds. Here is the script: $(function () { var timer, updateContent; function resetTimer() { if (timer) { window.clearTimeout(timer); ...