Clicking on the radio button will automatically update the <span> element

I have a DIV that contains a list of radio buttons and a 'selected search' area (a <span>). When the 'selected search' area is clicked, a drop-down layer appears with the DIV containing the radio buttons. Upon selecting a radio button, the text in the 'selected search' area updates to display the selected option, and the drop-down layer collapses.

Below is the HTML structure:

<div class="radio-btns"><span class="selected-search">A</span>
 <div class="radio-btns-wrapper">
  <label><input type="radio" value="a" id="a" checked>A</label>
  <label><input type="radio" value="b" id="b">B</label>
  <label><input type="radio" value="c" id="c">C</label>
  <label><input type="radio" value="d" id="d">D</label>
 </div>
</div>

If you have any suggestions on how to achieve this using jQuery, your assistance would be greatly appreciated.

Thank you.

** UPDATE **

Since I initially posted this question in 2010, my jQuery skills have improved. Here's an updated markup since the previous one could be better optimized.

New HTML structure:

<a href="#" class="selected-search">A</a>
<div class="radio-btns-wrapper">
    <label><input type="radio" value="a" id="a" name="radio" checked>A</label>
    <label><input type="radio" value="b" id="b" name="radio">B</label>
    <label><input type="radio" value="c" id="c" name="radio">C</label>
    <label><input type="radio" value="d" id="d" name="radio">D</label>
</div>

jQuery script:

This is an improvement based on @Greg's solution below:

//If JavaScript is enabled, hide the container for radio buttons
$(".radio-btns-wrapper").hide();

//The DIV with radio buttons will slide down when .selected-search is clicked
//Default behavior of the link <a> is prevented to avoid page jumping back to top
$(".selected-search").click(function (e) {
    $(".radio-btns-wrapper").slideDown();
    e.preventDefault();
});
//Clicking on a radio button updates the target text with the selected option's text
$("input[type=radio]").click(function () {
    // Update the text of the span to match the text of the clicked label
    $(".selected-search").text($(this).parent().text());
    // Hide the radio buttons
    $(".radio-btns-wrapper").slideUp();
});

As the suggested demo link no longer works, I have created my own demo which can be viewed here: http://jsfiddle.net/rzea/vyvLvgkh/4/

Answer №1

Check out this JsFiddle demonstration:

http://jsfiddle.net/g105b/VHBkP/ (demo no longer available on jsfiddle.net)

To see a live demo, click here: http://jsfiddle.net/rzea/vyvLvgkh/5/ - Refer to the updated markup and script in the edit above.

$(".radio-btns").click(function() {
    $(".radio-btns-wrapper").toggle();
});

$("input[type=radio]").click(function() {
    // Change the text of the span to match the label that was clicked.
    $(".selected-search").text($(this).parent().text());
    // Hide the radio buttons.
    $(".radio-btns-wrapper").hide();
});

Answer №2

Here is a helpful snippet to guide you:

$('span.selected-search').click(function(){
    this.next('div.radio-btns-wrapper').toggle();
});

Take a look at the documentation for more options on toggling: http://api.jquery.com/toggle/

Keep in mind that this code will only be effective if the desired span follows the selected-search span directly

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

Prevent Ajax form submission before transmission

I'm currently working with a content management system that generates a form and uses AJAX to submit it. I want to validate the input fields before submission, but the CMS automatically sends the form on the submit event. bind(form, "submit", functio ...

Using jQuery to create a flawless animation

I am currently working on an animation project, and I have shared my progress on jsfiddle. Below is the code snippet I have utilized: /* JavaScript: */ var app = function () { var self = this; var allBoxes = $('.box&apos ...

What is the counterpart of Ajax.updater in Jquery?

Could you please advise on how to achieve the same functionality as the prototype code below but using Jquery? var myAjax = new Ajax.Updater('abc', '/billing/add_bill_detail', { method: 'get', parameters: pars, ...

Effortlessly transfer various documents using the Struts2 framework combined with Dropzone.js

I am currently utilizing DropZone.js for file uploads. Here is my current configuration: Dropzone.options.myAwesomeDropzone = { url: 'UploadImages', previewsContainer: ".dropzone-previews", uploadMultiple: true, parallelUploads ...

Optimizing jQuery Dialog for Different Window Sizes

I am currently developing a responsive website and facing a challenge. I need to implement a popup for window sizes smaller than 480px, but on desktop screens, the content should be visible without being inside the popup. I want to avoid duplicating the co ...

"By utilizing jQuery, the form submission can be triggered through an AJAX call upon

I am having difficulties making this script work. I am trying to send a form via ajax by triggering submit after clicking on a div element. Below is the form code: <div title="add to Favorits" id="social1549" class="favtrigger nobtn transition"> ...

Navigating through Node's asynchronous behavior

I am currently developing a web scraper that gathers data about various shirts from a specific website. I have successfully set up all the necessary NPM packages in Node.js to scrape the information and save it to a CSV file. However, I have encountered ...

What steps should I follow to create an automatic image slider using Fancybox that transitions to the next slide seamlessly?

*I've recently ventured into web design and am currently experimenting with Fancybox. I'm interested in creating a slider with 3 images that automatically transitions to the next image, similar to what is seen on this website: Is it feasible to ...

How can I retrieve the Google Maps URL containing a 'placeid' using AJAX?

I have a specific URL that I can access through my browser to see JSON data. The URL appears as follows: https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJZeH1eyl344kRA3v52Jl3kHo&key=API_KEY_HERE However, when I attempt to use jQuer ...

Reference to children of jQuery DOM object

To improve the quality of my code, I am attempting to write event handler functions that are able to identify their source. It's unclear whether my approach is incorrect or if the nesting of divs within tables on the page is causing issues. The objec ...

Unable to allocate a second item to an existing one

Encountering an unusual issue while trying to assign an item a second time. Initial scenario: I am working with a jqxTree containing various items as shown below: - apple - oracle - microsoft When I drag and drop one item into another, the structure loo ...

Adding code containing various Google Maps elements in a fresh browser window using JavaScript

I've encountered an issue while trying to create a new page with a Google map and title based on the button clicked. Interestingly, when I copy/paste the HTML in the "newhtml" variable into an actual HTML file, it works perfectly fine. However, it doe ...

Looking for insights on reading and presenting XML files from a URL? Learn how to achieve this effortlessly with the power

Currently, I'm in the process of developing an innovative Android application using PhoneGap. My main objective is to dynamically present the data stored within a customized XML file hosted on my website that follows the .php format. Do you happen to ...

Update the second selection when the first selection is changed

Apologies for not including "my attempt" here, I struggle with jquery and need some guidance!! I want to modify the value of a second selector based on the outcome of the first. In my database, I have a list of builders and regions under the headings bui ...

Utilizing Jquery to retrieve an array as the return value from a $.post request

After going through numerous discussions on this topic, I'm still struggling to make it work. However, I've made significant progress. I have a scenario where I send data from jQuery to my database. The database returns a record consisting of two ...

Switch from scrolling the entire page to scrolling within a single div

Whenever I click on an element on my webpage, a modal window with a fixed position appears. The issue I am facing is that when I scroll using the mouse or touch gestures on my phone or tablet, the entire page scrolls instead of just the content within the ...

Unusual issue with jQuery's AJAX functionality

Utilizing jQuery AJAX, I am fetching data from a PHP page and displaying a loading GIF image in the placeholder to indicate that results are being processed. $(".project").change(function(){ $(".custName").html("<img src='/admin/images ...

Trigger the execution of a Python script through a webpage with just the click of a button

I have a small web interface where I need to control a Python script that is constantly gathering data from a sensor in a while loop. Ideally, I would like the ability to start and stop this script with the click of a button. While stopping the script is s ...

Once the auto-suggestion feature has completed its task

Utilizing the autocomplete Plugin, I have encountered an issue despite its great functionality. $('#request_song').autocomplete({ serviceUrl: '<%= ajax_path("trackName") %>', minChars:1, width: 300, delimiter: /(,|;)&bsol ...

Generating a JavaScript variable linked to a Rails Active Record relationship

I'm trying to implement an active record association in the DOM, but I'm encountering some difficulties. Here is my editor class: .editing .row .col-sm-3 .col-sm-8 .text-left #font-20 .title-font . ...