Modify the radio button's appearance by styling it upon clicking

I have designed an HTML structure to switch payment methods.

<ul id="checkout-method">
    <li><input name="payment_method" type="radio" value="Cash on Delivery" checked>
        <label>Cash on Delivery</label>
        <p class="explainpaymethod">Pay with cash upon delivery.</p>
    </li>
    <li><input name="payment_method" type="radio" value="Paypal">
        <label>Paypal</label>
        <p class="explainpaymethod">Pay via PayPal; you can pay with your credit card if you don’t have a PayPal account.</p>
    </li>
</ul>

However, I am unsure how to achieve the following:

  • Ensure that the first input is always checked by default.

  • Allow users to click on the parent li tag to select the radio button.

  • Show the relevant .explainpaymethod when one payment method is selected, and hide the others.

Thank you for any assistance provided.

Answer №1

  • Ensure the first radio button is selected by utilizing the checked property within the initial input tag.

  • If you want to click on the parent li tag instead of the radio button, apply the display: block; property to the <label>.

Here is a way to incorporate all these properties:

$(document).ready(function(){  

$("input[type='radio']").on('click', function(e) {
  $('p.explainpaymethod').hide();
  if($(this).is(':checked')) {
    $(this).closest('li').find('p.explainpaymethod').show();
    }
  })

});
label {
  display: block;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="checkout-method">
    <li><label><input name="payment_method" type="radio" value="Cash on Delivery" checked>
        Cash on Delivery</label>
        <p class="explainpaymethod" style="display:inline-block">[Pay with cash upon delivery.]</p>
    </li>
    <li><label><input name="payment_method" type="radio" value="Paypal">
        Paypal</label>
        <p class="explainpaymethod" style="display:none">[Pay via PayPal; you can pay with your credit card if you don’t have a PayPal account.]</p>
    </li>
</ul>

Trust this information proves helpful!

Answer №2

Always ensure the first input is checked.

To set the default selected option in HTML, utilize the checked attribute.

To check the radio, click on the parent tag li instead of the radio button itself.

Instead of adding a click event to the li, enclose both the input and text within a <label> element. This method enhances the clickable area for the radio button.

If one option is checked, display the .explainpaymethod; otherwise, hide it.

To accomplish this, you will need some JavaScript code. Hide all .explainpaymethod elements and only show the relevant one based on the changed radio button by utilizing DOM traversal techniques like closest() and find(). Here's an example:

$('#checkout-method input').change(function() {
  $('.explainpaymethod').hide();
  $(this).closest('li').find('.explainpaymethod').show();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="checkout-method">
  <li>
    <label>
      <input name="payment_method" type="radio" value="Cash on Delivery" checked="true">
      Cash on Delivery
    </label>
    <p class="explainpaymethod">Pay with cash upon delivery.</p>
  </li>
  <li>
    <label>
      <input name="payment_method" type="radio" value="Paypal">
      Paypal
    </label>
    <p class="explainpaymethod" style="display:none">Pay via PayPal; you can pay with your credit card if you don’t have a PayPal account.</p>
  </li>
</ul>

Answer №3

1) Ensure that the first "input" is always checked.

$('input[type="radio"]').eq(0).prop('checked',true);

2) To select a radio button by clicking on its parent li tag, use the following:

You can achieve this by using <label for="parent_id">

<label for="Paypal">Paypal</label>

3) When one radio button is selected, display the corresponding .explainpaymethod and hide others.

$('input[type="radio"]').change(function() {
   $('.explainpaymethod').hide();
   $(this).closest('li').find('.explainpaymethod').show();
});

$('input[type="radio"]').eq(0).prop('checked',true);
$('input[type="radio"]').eq(0).closest('li').find('.explainpaymethod').show();
$('input[type="radio"]').change(function() {
  $('.explainpaymethod').hide();
  $(this).closest('li').find('.explainpaymethod').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="checkout-method">
    <li><input name="payment_method" type="radio" value="Cash on Delivery" id="Cash">
        <label for="Cash">Cash on Delivery</label>
        <p class="explainpaymethod" style="display:none">Pay with cash upon delivery.</p>
    </li>
    <li><input name="payment_method" type="radio" value="Paypal" id="Paypal">
        <label for="Paypal">Paypal</label>
        <p class="explainpaymethod" style="display:none">Pay via PayPal; you can pay with your credit card if you don’t have a PayPal account.</p>
    </li>
</ul>

Answer №4

You can achieve this without the need for javascript.

Simply start by adding the checked attribute to the input that you want to be pre-selected by default.

Next, assign an "id" attribute to the inputs and a "for" attribute to the corresponding labels.

<ul id="checkout-method">
    <li><input name="payment_method" type="radio" checked value="Cash on Delivery" id="cod">
        <label for="cod">Cash on Delivery</label>
        <br>
        <p class="explainpaymethod">Pay with cash upon delivery.</p>
    </li>
    <li><input name="payment_method" type="radio" value="Paypal" id="pp">
        <label for="pp">Paypal</label>
        <br>
        <p class="explainpaymethod">Pay via PayPal; you can pay with your credit card if you don’t have a PayPal account.</p>
    </li>
</ul>

Then include the following CSS code which will display the paragraph if its sibling input is checked.

.explainpaymethod {
  display: none;
}
input:checked ~ .explainpaymethod {
  display: inline-block;
}

You can access the fiddle using the following link: https://jsfiddle.net/u1zjyorf/3/

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

Activate the button click event using JavaScript or jQuery automatically when the page is loaded in Internet Explorer

Currently, I'm faced with this code snippet: window.onload = function () { $('#btnFilter').click(function (e) { btnFilter(e); }); } The issue here is that the function only works when the button is clicked. What I actually ...

What methods can be employed to prevent a custom CSS from overriding my personal styles?

Issue I've created a website with unique styles that I really like. However, I want to enhance its functionality by incorporating a custom dialog box from the BootBox library. The problem is that the extensive style sheet that comes with BootBox com ...

Can someone help me troubleshoot the issue with my submit button's onclick function?

I am currently working on a project where I have a content box enclosed in a div tag. Within this content box, there are paragraphs with unique IDs for individual styling rules. I have set margins, padding, and other styles accordingly. At the bottom of th ...

The styled-components seem to be having trouble injecting the necessary CSS to handle all the various props

I am curious to understand the potential reasons for styled-components not injecting all the necessary CSS into a page's header. In an existing project, I have defined a simple button like this: const Button = styled.button` background-color: ...

Removing an item from an array stored in jQuery using the .data() method

Utilizing the .data() method in jQuery, I have saved an array as shown below: var myArray = {}; myArray[0] = {}; myArray[0][0] = "test00"; myArray[0][1] = "test01"; myArray[1] = {}; myArray[1][0] = "test10"; myArray[1][1] = "test11"; $('#datastorage ...

Employing JavaScript to insert a JSON value as a parameter in an HTML element's attribute

In a JSON file, I have "img" properties with .jpg file paths as their values (e.g "images/image.jpg"). I am attempting to insert these values into the 'src' attribute of existing HTML elements. Below are my attempts so far: I tried creating te ...

"Is there a way to implement the functions of adding, editing, and deleting data in

When attempting to display a table using jQuery DataTable, I would like to add edit and delete buttons at the last column of each row. How can I ensure that the database is updated with every edit and delete action? Ajax Request Example: //Ajax to get id ...

Contrasting $interval and setInterval functions in AngularJs

I am trying to grasp the distinction between $interval and setInterval. I have come up with this test: Dashboard.prototype.updateTotalAppointments = function(){ //console.log(); this.appointmentsCount = this.appointmentsCount +1; console.log(this.appointm ...

What is the best method to choose the following sentence once the final * has been identified

In the navigation text, my objective is to pick out the final sentence following * For example; Home*Development*Mobil and Web Development I am only interested in selecting the last sentence after * --> (Mobil and Web Development) ...

Attempting to iterate over a JSON object and display its contents using HTML

I have been attempting to iterate through this JSON data and display it in an accordion format similar to the one shown here: but unfortunately, my implementation is not functioning correctly. Here is what I currently have: HTML: <div class="a ...

Using just a simple HTML code, the d-flex feature in Bootstrap seems to be malfunctioning

Embarking on a new Bootstrap website project has presented me with a challenge that I have not been able to overcome, even with minimal HTML and just one flex item (which happens to be the only element on the site): <!DOCTYPE html> <html lang=" ...

Calculating in PHP through AJAX Call

Does anyone know how to increment a SESSION variable without the user experiencing any page refreshes? I have tried the code below, but it only updates once and then requires a refresh. Is there a way to achieve this without reloading the page? test page ...

How can I apply column spacing specifically for both desktop and mobile devices using only Bootstrap 4?

I am struggling to create a 15px gap between two rows and columns on both desktop and mobile using bootstrap. I know there is something with margins, but I can't figure out the best way to implement it. For the second row, I want two columns to appea ...

Attempting to create a dynamic grid layout utilizing CSS to ensure optimal responsiveness

I am working on creating a webpage layout similar to the one in the link below: The maximum width for the layout is set to 1600px. However, I am facing challenges in making it fully responsive. This is because all the boxes are given widths in percentages ...

NextJS compilation sometimes results in undefined errors when using Sass styles

My peace lies in the sass code: .link display: inline-table text-align: center align-self: center margin: 5px 15px font-size: 20px color: black text-decoration: none transition: 0.1s ease-in-out .link:hover text-decoration: underline .l ...

Utilize CSS styling on dynamically loaded HTML content

I am working on a project similar to the StackOverflow editor. I am fetching markdown text, converting it to HTML, and then displaying it in a preview area. However, when I try to style the injected HTML elements using CSS, the styles are being ignored. Up ...

Repurposing JavaScript objects after clearing their contents

Here's my issue. I'm working with a Javascript object, initialized as var stack = {}. This object is used in my project to store arrays. When the user clicks the add button, an array is added to the object with a specific key that is inputted in ...

Display a jQuery dialog box with options to confirm or cancel. Submit the form when the user clicks on

One of the functionalities on my website involves a jquery-ui modal dialog that pops up when a user clicks the "Decline" button on a control within an asp.net UpdatePanel. This feature is repeated multiple times on various controls across the page. Here&a ...

Angular: Ensuring Paypal button does not display twice without a hard reload

I have encountered an issue with a PayPal payment button on my page. The button displays fine when I generate it for the first time, but if I try to generate it again for another order, it doesn't show up. I have to hard reload the page to get it to w ...

Angular 6 seems to be having issues loading Bootstrap

I've run into an issue while trying to incorporate Bootstrap into Angular 6. I have already installed Bootstrap using npm install bootstrap and added it to angular.json, but it's still not functioning. Is there something else I should be doing? A ...