How can I retrieve the value of a selected radio button within a fieldset using jQuery?

I have a fieldset with two radio buttons inside. When a radio button is clicked, I want to retrieve the value of the clicked button. However, my current jQuery code is not functioning correctly and I would appreciate any assistance.

HTML:

<fieldset id="skin-complexion" name="properties[skin_complexion]">

  <img src="{{ 'icon-fair.png' | asset_url }}">
  <input type="radio" value="Fair" />
  Fair

  <img src="{{ 'icon-medium.png' | asset_url }}">
  Medium
  <input type="radio" value="Medium" />


</fieldset>

jQuery:

$('#skin-complexion').on('change', function() {

  var value = $(this).val();
  alert(value);      

});

My jQuery code above is not working. Any help is appreciated.

Answer №1

Make sure to use the radio selector when working with radio buttons

$('#skin-complexion input:radio').on('change', function() {
  var value = $(this).val();
  alert(value);      
});

Example of the code in action:-

$('#skin-complexion input:radio').on('change', function() {
  var value = $(this).val();
  console.log(value);      
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset id="skin-complexion" name="properties[skin_complexion]">

  <img src="{{ 'icon-fair.png' | asset_url }}">
  <input type="radio" value="Fair" />
  Fair

  <img src="{{ 'icon-medium.png' | asset_url }}">
  Medium
  <input type="radio" value="Medium" />


</fieldset>

Note:- To allow only one radio button selection at a time, assign a common name attribute to them

$('#skin-complexion input:radio').on('change', function() {
  var value = $(this).val();
  console.log(value);      
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset id="skin-complexion" name="properties[skin_complexion]">

  <img src="{{ 'icon-fair.png' | asset_url }}">
  <input type="radio" name="radio_example" value="Fair" />
  Fair

  <img src="{{ 'icon-medium.png' | asset_url }}">
  Medium
  <input type="radio" name="radio_example" value="Medium" />


</fieldset>

Answer №2

Consider using the jQuery selector

$('#skin-complexion > input[type=radio]')
to target specific radio buttons.

Make sure to assign a common name attribute to your radio buttons to ensure only one can be selected at a time:

$('#skin-complexion > input[type=radio]').on('change', function() {

  var selectedValue = $(this).val();
  alert(selectedValue);      

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset id="skin-complexion" name="properties[skin_complexion]">

  <img src="{{ 'icon-fair.png' | asset_url }}">
  <input type="radio" name="level" value="Fair" />
  Fair

  <img src="{{ 'icon-medium.png' | asset_url }}">
  Medium
  <input type="radio" name="level" value="Medium" />


</fieldset>

Answer №3

To ensure users can only select one radio button at a time, make sure to assign names to each radio button. If you want to allow users to select multiple radio buttons simultaneously, you can use the code snippet below:

$("#skin-complexion input[type='radio']").click(function(){
    console.log($(this).val());
});

If you need users to choose only one option, add names to each radio button like in the example below:

<fieldset id="skin-complexion" name="properties[skin_complexion]">

  <img src="{{ 'icon-fair.png' | asset_url }}">
  <input type="radio" value="Fair" name="type1" />
  Fair

  <img src="{{ 'icon-medium.png' | asset_url }}">
  Medium
  <input type="radio" value="Medium" name="type1" />


</fieldset>

To retrieve the value of the selected radio button, use the following script:

$("#skin-complexion input[type='radio']").click(function(){
    console.log($(this).val());
});

This should provide the functionality you need!

Answer №4

If you're looking to expand your knowledge on attributes in jQuery, I recommend checking out this resource: https://api.jquery.com/attribute-equals-selector/

$('#skin-complexion input[type="radio"]').on('change', function() {

  var selectedValue = $(this).val();
  alert(selectedValue);      

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset id="skin-complexion" name="properties[skin_complexion]">

  <img src="{{ 'icon-fair.png' | asset_url }}">
  <input type="radio" value="Fair" />
  Fair

  <img src="{{ 'icon-medium.png' | asset_url }}">
  Medium
  <input type="radio" value="Medium" />


</fieldset>

Answer №5

For radio buttons in the same group, it is important to assign a name attribute. This allows you to select the value when clicked and display it in an alert.

$('input[type=radio][name=myRadios]').on('change', function() {

  var value = $(this).val();
  alert(value);      

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset id="skin-complexion" name="properties[skin_complexion]">

  <img src="{{ 'icon-fair.png' | asset_url }}">
  <input type="radio" value="Fair" name="myRadios" />
  Fair

  <img src="{{ 'icon-medium.png' | asset_url }}">
  Medium
  <input type="radio" value="Medium" name="myRadios"/>


</fieldset>

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

I am looking for a way to batch upload several images from an HTML page to a nodejs server, where I can then rename and

Exploring the world of nodejs, I am seeking guidance on updating multiple images from HTML to node js. Specifically, how can I rename each image differently and save them to a directory? Alternatively, is there another solution that would better suit my ne ...

Alter the page's color scheme completely

I am currently facing an issue with my button that creates a popup and darkens the background of my page. While this functionality works, it does not affect any bootstrap containers. I am using bootstrap 4 and react for this project. https://i.sstatic.net/ ...

React application not displaying element properly?

I am facing an issue with my react modal that displays a sign-in and sign-up form. The problem arises when I try to access the button on the form using its id, which is modal-sign-in-submit-button. document.getElementById('modal-sign-in-submit-button ...

I attempted to apply vertical-align and color properties to the static_nav div, but they didn't have any effect. Could this be due to its placement within the header? What steps should I take to resolve this issue?

<!DOCTYPE HTML> <html lang ="en"> <meta charset = "utf-8" /> <head> <title>Sample Page</title> <link rel="stylesheet" type="text/css" href="Web_Design_01_Stylesheet.css" /> </head> <body> &l ...

Tips for adjusting image and div sizes dynamically according to the window size

In my quest, the end goal is to craft a simplistic gallery that closely resembles this particular example: EXAMPLE: This sample gallery is created using Flash technology, but I aim to develop mine utilizing HTML, CSS & Javascript to ensure compatibil ...

How come the last word in CSS nested flexbox wraps even though there is space available?

I am facing an issue with a nested flex container setup. Below is the code snippet: <div class="parent-container"> <div class="child-container"> <span class="color-block"></span> <span>T ...

Is your jquery draggable bouncing around unexpectedly on the page when released?

I'm currently troubleshooting the issue of jquery ui draggable moving unexpectedly when released onto the droppable area! The element seems to be shifting to the right regardless of where it is dropped on the page! To better illustrate the problem, ...

What steps should I take to ensure that this 3D transformation functions properly in Internet Explorer 10?

I'm struggling to get a CSS 3D transform to function properly in IE10. The issue arises because IE10 lacks support for the preserve-3d property. According to Microsoft, there is a workaround available. They suggest applying the transform(s) of the pa ...

Handsontable: How to update renderers when a row is deleted

Implementing Handsontable into our reporting system has been a success, except for one issue. I am using renderers to highlight error cells by setting the background color to red. However, when I remove a row using the context menu's "remove row" opti ...

Creating a responsive navigation menu by converting overflowing menu items into a dropdown list

I'm currently designing a menu that contains multiple list items. I would like the overflowing li's to collapse and display in a dropdown when resizing the browser to smaller screens, such as laptops and tablets. Original Menu. https://i.sstatic ...

MailJet experienced a template language issue while trying to send a message with Template [ID]

While running a test on a MailJet email template that includes a basic custom HTML code block, an error occurs in the received test email. (The live preview in the browser functions correctly) From [email protected]: An issue with the template lang ...

Jekyll adjusting the starting line of code snippet formatting

Currently, I'm in the process of setting up code highlighting for my blog using Jekyll and Pygments. However, I'm facing an issue where the first line of every code snippet seems to be slightly offset. To create a gutter effect, I'm utilizin ...

Encountered Runtime Issue of TypeError: undefined cannot be iterated (unable to access property Symbol(Symbol.iterator))

I've been working on a multiselect feature in my Next.js project, utilizing states and setting them accordingly. However, I keep encountering this specific error: https://i.stack.imgur.com/m8zuP.png whenever I click on this: https://i.stack.imgur.c ...

What is the best way to delay JavaScript execution until after React has finished rendering?

Perhaps this is not the exact question you were expecting, but it did catch your attention :) The issue at hand revolves around the fact that most of the translations in my text do not update when the global language changes. Specifically, the translation ...

Keeping datetimepicker current when a date is chosen - a guide

I am currently utilizing the datetimepicker plugin from xdsoft to enable users to select a booking date and time. Check out the documentation for more details. To manage bookings, I have set up a 'fechas' table in my database which stores inform ...

How to center elements using Bootstrap 4 and flexbox styling

Just starting out in web development. I currently have the following HTML: <section class="boxes"> <div class="container-fluid"> <div class="row"> <div class="col-12 col-lg-4 box1&q ...

An issue with the form.submit function within an if-else statement

Can anyone help me with submitting a form using AJAX within an if-else statement? I have the code below, but it doesn't seem to be working as expected: $.ajax({ type: "POST", url:'<?php echo base_url() ?>signup/orde ...

The JavaScript file failed to load

My HTML code is having trouble loading all the files. The Javascript files UserController.js and RepoController.js are not being loaded, which means they are not displayed in the developer tools source tab. When I press F5 in the network tab, the files are ...

Tips on how to maintain the value of an integer variable even after clicking a submit button, enabling its reuse on the same page

Take a look at the first part of this code where we are using the variable $Tno. if(isset($_POST['submit'])) { $Tno=$_POST['Tno']; $query="SELECT * FROM docs WHERE Tno='$Tno'"; $result=mysql_query($query) or di ...

Initiate a JavaScript confirmation dialog using server-side logic in ASP.NET

Does anyone know how to troubleshoot the issue with this code? I am trying to make it so that when btnOne is clicked and a is true, a confirm box pops up. If yes is selected, then it should execute the btnTwo method. Currently, the popup isn't appeari ...