Sending Radio Button Selection Multiple Times

I've been working on a code snippet that takes the selected value of a radio button and transfers it to a group of radio buttons for further use. The first pass works perfectly fine, but subsequent passes end up transferring "on" instead of the intended value. I believe it's just a minor issue, but I haven't been able to pinpoint it yet.

Access the JS Fiddle link here: https://jsfiddle.net/hc3bracf/6/

Below is the HTML and JS code:

<div class="container">
  <ul class="aaa">
    <li>
      <input type="radio" name="g1" id="i1" value="s#1" data-target="r65">
      <label id="r1" for="i1">s#1</label>
      <div class="check">
        <div class="inside"></div>
      </div>
    </li>
    <li>
      <input type="radio" name="g1" id="i2" value="s#16" data-target="r65">
      <label id="r2" for="i2">s#16</label>
      <div class="check">
        <div class="inside"></div>
      </div>
    </li>
  </ul>
</div>

(remaining HTML code continued with similar structure)

JS Code:

const inputs = document.querySelectorAll("input[type=radio]");
for (let inp of inputs) {
  inp.addEventListener("change", function() {
    let targetLabel = document.getElementById(inp.dataset.target);
    let targetRadio = targetLabel.previousSibling;
    targetLabel.innerHTML = inp.value;
    targetRadio.value = inp.value;
    targetRadio.checked = false;
    
    while (targetLabel.previousSibling.hasAttribute) {
      targetLabel = document.getElementById(targetRadio.dataset.target);
      targetRadio = targetLabel.previousSibling;
      targetRadio.checked = false;
      targetLabel.innerHTML = '';
    }
  });
}

Answer №1

The previousSibling attribute retrieves the node that precedes the specified node at the same tree level.

This retrieved node is in the form of a Node object.

It's important to note that this attribute differs from previousElementSibling in that previousSibling can return various types of nodes such as element, text, or comment nodes, whereas previousElementSibling specifically returns an element node excluding text and comment nodes.

const radioInputs = document.querySelectorAll("input[type=radio]");

for (let input of radioInputs) {
  input.addEventListener("change", function() {
    let targetLabel = document.getElementById(input.dataset.target);
    console.log(targetLabel);
    let targetRadio = targetLabel.previousElementSibling;
    
    targetRadio.value = input.value;
    targetLabel.innerHTML = input.value;
   
    targetRadio.checked = false;
    // Clear next target elements if they exist
     while (targetLabel.previousElementSibling.hasAttribute) {
      targetLabel = document.getElementById(targetRadio.dataset.target);
      targetRadio = targetLabel.previousSibling;
      targetRadio.checked = false;
      targetLabel.innerHTML = '';
    }
  });
}

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

Jquery is unable to detect duplicate class names

if ($(".event_list")[0]){ if($(".event_list").find(".type").length == 0 && $(".event_list").find(".sold").length == 0) { $(".event_list").click(); } } else { $('#something').click(function() { location.reload(); }); } I attemp ...

Customizing split applications on Windows 8

Windows 8 split app displays tiles with images, and I want each tile to show a different image. Below is the code from the default.html page: <div class="item"> <img alt="some text" data-win-bind="source: imagePath"> <div class="item-overl ...

Utilize ng-repeat to iterate over two arrays

Two arrays are at my disposal here. The first array contains option content, while the second array consists of option tags (i.e., A, B, C, D). How can I structure the layout for the 'input type="radio"' using ng-repeat? To start off, I am attem ...

Developing real-time chat functionality in React Native with node.js and Socket.io

I'm on the lookout for resources to help me navigate both server-side (mostly) and client-side development. I recently came across a resource called Simple Real Time chat app but unfortunately, it did not yield significant results. I tried locally ho ...

Timing with Three.js - the key to engaging interactive experiences

Lately, I've been discovering some amazing interactive shorts created with three.js. Take a look at this example: I'm curious about the timing mechanism used in these creations. Are there any known libraries for that? The synchronization of mu ...

How can I update a particular label with Ajax?

I have encountered an issue where I am attempting to dynamically update a label every 5 seconds using AJAX and interval in my Webforms application. However, the label only updates when I manually refresh the page. It does not change without reloading the p ...

I am looking to identify when a user clicks outside of a specific Div element on a webpage using JavaScript

Is it possible to detect when a user clicks outside of a specified div using JavaScript? <script> function detect(){ alert("Detect"); } //Looking for a way to determine when a click occurs outside of this div </script> &l ...

Display the query results on a separate blade

In my original attempt, I intended to display the results in a modal but later decided to show them in a different blade. My goal is to fetch all comments related to a post using its post_id. However, I encountered the following error: The GET method is no ...

What is the best way to display the currently selected value in a Vue select drop down?

Is there a way to make the selected item in a custom component dropdown appear, similar to this Vue.js question? I have debug output within my single file component (SFC). <script> export default { props: ['modelValue', 'options&apos ...

Struggling to get CORS request to function properly

I am encountering a CORS issue while trying to retrieve data from a webservice on a different domain. Within my controller, I have the following code: $http({method: 'GET', url : 'http://somewebserviceapi.com?idAppli=' + appId, header ...

Schema for Monogo Database

My goal was to have a property that could give me the timestamp of when a specific task was created. I decided to add a timestamp property and set it to true, but now my code won't compile. The code is functioning perfectly fine without the timestamp ...

Guide on scheduling MongoDB calls with Node.js recursively

Is there a way to trigger this code or function periodically? I am considering using setInterval, for example: setInterval('function()', 5000);. However, I am unsure about how to implement it in this specific scenario. list = []; MongoClient.conn ...

Challenges with Performance in IONIC Mobile Applications

Currently, we are in the final stages of developing a high-profile mobile application for one of our clients using the IONIC framework. The application performs well when accessed through a Web/Mobile Browser. However, once it is ported into a mobile appli ...

What is the best approach for sending extremely lengthy data through an AJAX URL?

Currently, I am utilizing PHP and AJAX simultaneously to obtain user data and insert it into the database. The issue arises when trying to send a large string of 10000 characters, as the browser displays an error stating that the URL is too long. While I ...

Transform my Curl script into a NodeJS app

I'm trying to replicate the functionality of a curl command within my NodeJS application, but I am facing some difficulties. Any guidance on how to achieve this would be greatly appreciated. curl -H "Authorization: bearer $TOKEN" If I already hav ...

How do I retain the user's color choice using jQuery cookies for future visits?

I've created a jQuery color picker that allows users to save their color selection with just one click. You can see the color picker in action here: http://prntscr.com/7rnafa . To handle the saving of color selections, I'm using a helpful jQuery ...

A guide on calling a function from a different component in vuejs2

I am facing a situation where I need to trigger an event whenever my sidebar opens. This event should be called every time the sidebar is opened. For example, when I click on an element, it triggers the opening of my sidebar which then calls a function th ...

Turn off error notifications from eslint parsing

Within my code, there is a conditional export that looks like this: if (process.env.NODE_ENV === 'testing') export myFunc; While in es6, this type of statement is typically not allowed due to the requirement for imports and exports to be top- ...

Sticky header in React data grid

Is there a way to implement a sticky header for a data grid in react? I have tried various methods but haven't been able to figure it out. Any suggestions would be appreciated. You can find my code sandbox example here. #react code export const Styl ...

Obtain a compilation of items present in every tier of nesting

{ "Alice Smith": { "Age": 20, "Gender": "F" }, "Bob Johnson": { "Age": 22, "Gender": "M" }, "Eve Michaels":{ "Age": 25, "Gender": "F" } } Can someone assist me in obtaining an array w ...