Steps for Choosing Radio Button by Clicking on Label and Transmitting Information to URL

When clicking on a "label", I want to be able to select a radio button and pass that value to the URL.

Below is the URL Prefill code.

If you click on the label, the radio button does not get selected. To solve this issue, I added some jQuery code at the top. However, it doesn't pass the value to the URL.

I'm interested in stylizing radio buttons by hiding the input part and adding pseudoclasses. Is there a way to pass the radio button value when the label is clicked on?

Answer №1

In order to select a radio button when clicking the label, there is no need for JQuery code. You can achieve this by using the following code:

<label for="regular">
  <input type='radio' name='product-choice' value='regular' id="regular" /> regular
</label>

To make this work, ensure that the ID attribute is set in the textbox and use that ID attribute value in the label's 'for' attribute.

Below is the complete code example:

<form id='form-product-choices' action=''>
    <main role="main">
        <section id="p1">
            <ul>
                <li>
                    <label for="regular">
                        <input type='radio' name='product-choice' value='regular' id="regular" /> regular
                    </label>
                </li>
                <li>
                    <label for="double">
                        <input type='radio' name='product-choice' value='double' id="double" /> double
                    </label>
                </li>
                <li>
                    <label for="xl">
                        <input type='radio' name='product-choice' value='max-xl' id="xl"  /> xl
                    </label>
                </li>
            </ul>
            <a class="quizbut">Next</a>
        </section>

        <section id="p4">
            <a id='action-link' class='quizbut' href='javascript:void(0)'>Click to continue</a>
        </section>
    </main>
</form>

<script type="text/javascript">
    $("#action-link").click(function(){
        var getVal = $('input[name=product-choice]:checked').val();
        window.location.href='https://example.com/test.cfm?product-choice='+getVal;
    });
</script>

Answer №2

Ensure that each radio button has a unique id associated with the corresponding for attribute on the label.

$(function(){

$('li').click(function(){$(this).find('input[type=radio]').prop('checked', true);});

});

/* URL Prefill Code */
var form = document.getElementById('form-product-choices');
  form.addEventListener('change', function(e){
  
     var actionUrl = 'https://example.com/';
 
 var radioButtons = document.getElementsByName('product-choice');
        for( var i = 0; i < radioButtons.length; i++ ) {
          if( radioButtons[i].checked ) {
            actionUrl += '?product-choice=' + radioButtons[i].value;
            break;
           }
         }
     document.getElementById('action-link').href = actionUrl;
     
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<form id='form-product-choices' action=''>

<main role="main">

<section id="p1">
<ul>
<li><label for="regular"><input id="regular" type='radio' name='product-choice' value='regular' /> regular</label></li>
<li><label for="double"><input id="double" type='radio' name='product-choice' value='double'  /> double</label></li>
<li><label for="max"><input id="max" type='radio' name='product-choice' value='max-xl'  /> xl</label></li>
</ul>
<a class="quizbut">Next</a>
</section>
    
<section id="p4">
<a id='action-link' class='quizbut' href=''>Click to continue</a>
</section>

</main>
</form>

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

Triggering a new window on button click with Vue and Nuxt

Having an issue with a button click event in Vue that opens a PDF using window.open(). It's working well on all browsers except for Safari on MAC. Any ideas what could be causing this? Should I pass $event to the method? <div class="button-do ...

The Angular ChangeDetection mechanism is failing to accurately display the correct data

I encountered a challenging situation that I am unable to resolve. My current project is built on Angular 6. I have designed a form that resembles a table using ngFor, allowing users to add rows dynamically. <table class="table"> <thead> ...

Comparing the Length of JavaScript Arrays

I have code that checks for similar values in two arrays, and if there are any, they are not displayed in the result. However, when I switch the lengths of the arrays so that Array2 is longer than Array1, I end up with an empty result array. How can I achi ...

Transitioning from using sendfile() to sendFile() function within the Express framework

Here is the code snippet I am using: router.get('/image',(req,res,next)=>{ const fileName = "path_to.jpg" res.sendfile(fileName,(err)=>{ if (err) { next(err); } else { console.log('Sent:', fileName); } ...

Retrieving information from the browser's IndexedDB and then initiating a call to the

Below is the useEffect callback function that I am currently using: import { initDB, useIndexedDB } from "react-indexed-db"; initDB(DBConfig); const db = useIndexedDB("reads"); useEffect(() => { db.getByIndex("hash ...

Error Occurs When Attempting to Call ASPX Codebehind Function from JavaScript

I am having trouble calling a function in the codebehind of my .aspx page once the window is fully displayed. I attempted to use the following code: <script type="text/javascript"> $(document).ready(function () { PageMethods.CheckFor ...

The toggle feature is malfunctioning following the integration of an Ajax call

When the combobox is clicked, an AJAX call is triggered. The toggling functionality works as expected without the AJAX call. You can see it in action here: http://jsfiddle.net/KxXuM/28/ However, once I added AJAX to append dynamic data to the combobox op ...

Removing an item from an array while also updating one of its attributes in JavaScript

I am facing a challenge with this list of objects: const flights = [ { id: 00, to: "New York", from: "Barcelona", cost: 700, scale: false }, { id: 01, to: "Los Angeles", from: "Madrid", cost: 1100, scale: tru ...

Following the completion of every asynchronous operation, a callback will be executed

I am facing a situation where I have an array of images that are uploaded with a series of asynchronous operations as shown below: for ( let key in imageFileObject ) { const imageFile = imageFileObject[key] dispatch('get_signed_request', ima ...

What is the method to exhibit the outcome of a promise on a web page within a React component?

In my search for information about promises, I have noticed that most articles provide examples using console.log. However, I am faced with a different scenario. I am working with AWS Athena and I need to display the result on a webpage in my React export. ...

What is the best way to toggle between display:none and display:block?

How can I delay the appearance of mobile nav items without using JS until the nav overlay fully expands for 0.4s? In the non-overlay state, the top nav has a hamburger menu on the left and my name on the right with hidden nav links. When in the overlay s ...

Uncovering the faces that grace the screen: A guide on finding them

When a user is navigating through a scene in my application, I want to be able to identify the visible faces on the screen (excluding those that are not in the camera's field of view or hidden by other objects). One approach I considered was using th ...

Retrieve the .js file from a WordPress plugin

I need assistance with loading a .js file from a WordPress plugin. Within the main plugin file, I have code that loads jQuery, jQuery-UI, and my .js file: //Load Java and Jquery function load_jquery() { // only use this method if we're not in wp ...

What is the best way to modify a large portion of JSON data in a nodejs environment?

I am currently working with two separate JSON files - data.json and dataForUpdate.json The contents of data.json are as follows: [{"name": "test", "isDefault": true, "settings": { "type": "Separation", "scanner": { "brightness": 0 ...

What is the best way to retrieve a value from a button function in order to utilize it in AJAX requests and SQL queries?

Having an edit button that allows users to change category names. When the edit button is clicked, a pop-up alert appears with an input field. Users can type in the input field, press okay, and the value should update with the input. This is the current co ...

Modify the width to fit the available space using flex containers

I'm currently working on adjusting the width of a container in case it cannot accommodate an additional character box. IMAGE: Eliminate excess spacing by resizing the width Here is the HTML code <section id="list_users"> <div i ...

An effective method to arrange divs in a line adjacent to each other

Apologies for the repetitive question, but I am in need of some answers. In my opinion: Having 1 div with a width of 100% and 2 divs inside each with a width of 50%. Why does it not fit properly? HTML: <div id="top-menu"> <div id="logo">& ...

Looking to alter the CSS of an ID element when hovering over a link on your website?

Irrespective of the positioning of the links in the html, a simple hover effect can trigger changes like switching images or altering backgrounds anywhere on the website. The ideal solution would involve a straightforward method without the need for Javas ...

Utilizing the default values in a Pebble AppSync Tuple

After making a few adjustments to the Pebble weather example program, I encountered an issue. I included some app_log calls for debugging purposes, and I decided to utilize a configuration screen instead of an app to transmit data. However, the app_log cal ...

Add 1 to the count if the order ID is located in local storage

let items = JSON.parse(localStorage.getItem('cart')) || []; let newItem = {}; $.each(items, function () { if (newItem.order_id == this.order.id) { newItem.order_id = '1'; newItem.order_name = 'cake'; ...