Using JavaScript to transform radio buttons into checkboxes

I have a grouping of radio buttons and a checkbox displayed on the page as shown below

<html>
<head>
    <title>Languages</title>
    <script type="text/javascript">

    </script>
</head>
<body>
    <span>What language do you speak?</span>
    <form action="">
    <div id="controlArea">
        <input type="radio" name="lanRadio" value="radioRussian"><label for="radioRussian">Russian</label><br />
        <input type="radio" name="lanRadio" value="radioEnglish"><label for="radioRussian">English</label><br />
        <input type="radio" name="lanRadio" value="radioSpain"><label for="radioRussian">Spanish</label><br />
        <input type="radio" name="lanRadio" value="radioFrench"><label for="radioRussian">French</label><br />
        <input type="checkbox" name="checkIn" value="CheckMore"><label for="CheckMore">Select more than one</label><br />
    </div>
    </form>
</body>

The goal is to allow users to switch between selecting multiple options when the "Select more than one" checkbox is ticked. If unchecked, the selection should revert back to only being able to choose one option. Additionally, when converting from radio buttons to checkboxes, the selected radio button should automatically be checked in the converted format.

Answer №1

Consider implementing the following solution:

function toggleInputType(inputElement) {
    // Define initial state as 'radio'
    var state = "radio";
    if (inputElement.checked) {
        state = "checkbox";
    }
    
    // Change type of all elements with matching name
    var elements = document.getElementsByName('lanRadio');
    for (var i = 0; i < elements.length; i++) {
        elements[i].type = state;
    }
}​

Don't forget to include an onclick handler on your checkbox :

<input type="checkbox" name="checkIn" onclick="toggleInputType(this)" value="CheckMore">

View example here

Answer №2

Give this a try! Just copy and paste the provided code snippet


        <html>
    <head>
        <title>Language Options</title>
        <script type="text/javascript">
    if(document.getElementById("radio1").type=="radio")
        {
            document.getElementById("radio1").type="checkbox";
            document.getElementById("radio2").type="checkbox";
            document.getElementById("radio3").type="checkbox";
            document.getElementById("radio4").type="checkbox";
        }
        else
        {
            document.getElementById("radio1").type="radio";
            document.getElementById("radio2").type="radio";
            document.getElementById("radio3").type="radio";
            document.getElementById("radio4").type="radio";
        }
        </script>
    </head>
    <body>
        <span>Which languages are you fluent in?</span>
        <form action="">
        <div id="controlArea">
            <input type="radio" id="radio1" name="lanRadio" value="radioRussian"><label for="radioRussian">Russian</label><br />
            <input type="radio" id="radio2" name="lanRadio" value="radioEnglish"><label for="radioRussian">English</label><br />
            <input type="radio" id="radio3" name="lanRadio" value="radioSpanish"><label for="radioRussian">Spanish</label><br />
            <input type="radio" id="radio4" name="lanRadio" value="radioFrench"><label for="radioRussian">French</label><br />
            <input type="checkbox" name="checkIn" value="CheckMore" onchange="fnc()"><label for="CheckMore">More than 1 language</label><br />
        </div>
        </form>
    </body>

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

Nodejs encountering error message during file download captured by a developer

I am attempting to download a file from nodejs. If there is an error on the backend, I need to display a message on the front end. The issue is that I cannot seem to capture that message. I suspect there may be some issues related to using blob and json ...

Rows that have been removed from an HTML table remain within the ReactDOM

After diving into JavaScript three months ago, I recently began learning React.js just two days back. While creating a simple TODO app, I noticed that when deleting a row, it disappears from the DOM but not from the React DOM. Can anyone shed some light ...

What can be done to prevent function from being treated as instance members within a controller's scope?

When using angularJS 1.3, the following code snippet showcases the functionality: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="http ...

Can a variable name be created using a function input?

It seems like my title might be a bit confusing, but oh well. I'm currently working on developing a game and I have several arrays named things like ItemsInG5Array, ItemsInB2Array. These names correspond to different nodes on the map. What I'm ai ...

Issue: Module 'connect' is not found?

Hey there! I'm fairly new to the world of servers, and I've been learning by watching YouTube tutorials. Following one such tutorial, I installed 'connect' using npm in my project folder. Here's the structure of my project: serv ...

Exploring the use of properties in JavaScript

I recently began learning Vue.js 2, but I encountered an issue when passing props to a child component. Here's the code snippet where I pass the prop: <div class="user"> <h3>{{ user.name }}</h3> <depenses :user-id="user.id"&g ...

Similar to TypeScript's `hasOwnProperty` counterpart

When working with TypeScript objects, is there a way to loop through a dictionary and set properties of another dictionary similar to how it is done in JavaScript? for (let key in dict) { if (obj.hasOwnProperty(key)) { obj[key] = dict[key]; } } If ...

"The issue of Django showing a 'select a valid choice' error when trying to populate a select field

I encountered a validation error while trying to create a form with an empty select field: area_sp = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form-control', 'id':'area_select'})) After populating the ...

Refresh the information displayed in the open Google Maps Infowindow

Experimenting with extracting JSON data from a bus tracker website and integrating it into my own version using Google Maps. Although not as visually appealing, I'm struggling to update an infowindow while it remains open. Despite finding some example ...

Exploring the resolution of unit test for an Angular Bootstrap modal using the John Papa ViewModel style

A custom ModalService has been created to display two different types of dialogs, CancelDialog and ErrorDialog, based on the parameter passed to the service. For example, the following code will show an ErrorDialog: ModalService.openModal('Analysis ...

What is the best way to dynamically populate a table with JSON data that is received from an API response?

Currently, I have a table that contains the FORM element: <table id="example" class="sortable"> <caption><h3><strong>Product inventory list</strong></h3></caption> <thead> <tr ...

Can you explain the contrast between img.height and img.style.height?

I'm currently in the process of resizing a series of images by iterating through an array and adjusting their sizes. if(items[0].height > 700 || items[0].width > 700){ items[0].style.height = "700px"; items[0].style.width = "700px"; } As ...

Tips for inserting the <a> HTML tag into a JSON array object

I am relatively new to creating array objects and I am unsure on how to add a link within a <a> tag in a JSON file. Here is the JSON object code: powerUpList: [ { id: 8, name: 'Automate your API column type ', description: & ...

Disable the mouseenter event in jQuery when the window is resized

I am facing a challenge with my code. I have two different functions that are triggered based on the screen size - one for desktop and one for mobile. The issue arises when transitioning from a desktop to a mobile view, as the hover/mouseenter effect still ...

Preventing jQuery slideToggle functionality from toggling multiple elements at once

I am currently working on a project where I have a series of images with captions that appear underneath each one. To show or hide the caption for each image, I am using slideToggle when the image is clicked. $('.imageholder').click(function() ...

The organizational chart function was functioning properly on the local environment, however, it failed to work after deployment, resulting in the error message "jQuery(

Currently, I am in the process of creating an organizational chart using the Angular library called orgchart. The code I have developed works fine on my local machine, but when we deploy it onto our nginx server, we encounter an error related to jQuery. T ...

Retrieve the selected option from the dropdown menu in the specified form

What should I do if I have numerous products and want users to be able to add new dropdown boxes dynamically? When the submit button is clicked, only the value of "category[]" within the form should be retrieved. https://i.stack.imgur.com/v1fnd.png Below ...

Inheritance from WebElement in WebdriverIO: A Beginner's Guide

I am seeking a solution to extend the functionality of the WebElement object returned by webdriverio, without resorting to monkey-patching and with TypeScript type support for autocompletion. Is it possible to achieve this in any way? class CustomCheckb ...

Finding a character that appears either once or thrice

In my work on JavaScript regex for markdown formatting, I am trying to match instances where a single underscore (_) or asterisk (*) occurs once (at the beginning, end, or surrounded by other characters or whitespace), as well as occurrences of three under ...

A guide on utilizing the index column for multiple tables using just one statement in the datatable js library

I've incorporated the datatable js for managing two tables on a single page. HTML <!-- Table#1 --> <table class="dataTable"> <thead> <tr> <td>#</td> <td>col1</td> </tr> &l ...