Vanilla Javascript: Create Radio Buttons (How-To)

Bhuman Soni
Bhuman Soni July 8, 2020
Updated 2022/01/26 at 9:42 AM
Frameworks such as Angular, React etc make dynamic DOM elements generation a breeze!! hence it’s easy to forget how to do so without any framework. Like one of my previous posts, in this post, we will look at how to create radio buttons and test t. However, before we move on to the solutions, let’s address an important question,

Should we know Vanilla Javascript?

I mean, in the light of the aforementioned awesome frameworks (Angular, React, Vue), would we ever use this information? Maybe? or maybe not? Javascript frameworks come and go. Remember JQuery? Remember how almost everyone was using that, it was such a big thing. Using JQuery in your Javascript project was almost second nature. Then there were frameworks like Backbone.js, Ember.js that emerged and saw a rise in popularity. Then there was AngularJS (Angular 1.x), then React and then the most recent edition, Vue.js. React did something new i.e. it introduced Virtual DOM which was a new concept to me. Not sure if Vue.js follows along that path? I haven’t used Vue.js yet. Anyway, all these frameworks are built on top of vanilla Javascript. Hence, it knowing how it all works under the hood cannot hurt and it may even help debug certain problems. Having said all that, let’s build something simple. Disclaimer: I am just trying to make a point here, this is by no means an thorough and exhaustive recollection of the lifetime of Javascript frameworks. 

What are we doing?

In this post, we are going to create four radio buttons in Javascript with certain values and test our code using JEST.

The code (Vanilla Javascript)

function radioButtons() {
    let totalElems = 4;
    const groupName = "radioGroup";
    let radioButtons = [];
    for(let idx=0; idx < totalElems; idx++) {
        let input = document.createElement("input");
        input.name = groupName;
        //+1 so we don't label them according to their index position
        input.value = (idx+1); 
        input.type = "radio";
        //let's set the last element to checked
        if(idx === 3) {
            input.checked = "checked";
        }
        radioButtons.push(input);
    }
    return radioButtons;
}

module.exports = {
    radioButtons: radioButtons
}
I think the above code is fairly straight forward and it has comments it’s got comments to help you understand. All, we are doing is generating four input elements using the document.createElement, setting them to be radio buttons and adding them to a collection. Let’s review a few key lines from the above code,
  1. A new input element is created via input = document.createElement 
  2. To ensure all radio buttons apply to the same group, set input.name property
  3. A radio button is set via input.type = “radio”;
  4. A radio button is marked as checked via input.checked = true, we only do that for the last input element in the above code
  5. Lastly, we export our function via the module.exports, so we can test it

Subscribe & never miss a post

Speaking of testing this code,

The test class for above

const genDomModule = require("./generateDom");

describe("Determine whether we generate dom elems properly", () => {
    test("Function generates 4 radio buttons", () => {
        let buttons = genDomModule.radioButtons();
        expect(buttons.length).toBe(4);
    });
    test("Generate all radio buttons", ()=> {
        let buttons = genDomModule.radioButtons();
        let allRadioBtns = true;
        for(let btn in buttons) {
            if(buttons[btn].type !== 'radio') {
                allRadioBtns = false;
            }
        }
        expect(allRadioBtns).toBe(true);
    });
    test('Expect radio button at index 1 to not be checked', () => {
        let buttons = genDomModule.radioButtons();
        expect(buttons[1].checked).toBe(false);
    });
    test("Expect radio btn at index 3 to be checked", () => {
        let buttons = genDomModule.radioButtons();
        expect(buttons[3].checked).toBe(true);
    });
    test("Check if the radio button values are init properly", () => {
        let buttons = genDomModule.radioButtons();
        expect(buttons[1].value).toBe("2");
    });
});
Again, the code for the test above should be easy to understand, if not, then please leave a comment and ask me.

How to run it?

You can simply navigate to the directory on command line and run it by executing npm run test. Alternatively, you can checkout the Github repository for this project, have a look at the source code and follow instructions to execute this code.

Summary

Every once in a while it’s good to have an understanding of these Javascript make all the magic happen under the hood.

Subscribe & never miss a post

As usual, if you find any of my posts useful support us by  buying or even trying one of our products and leave us a review on the app store. [appbox appstore 1020072048] [appbox appstore 1501784723] [appbox appstore 1066820078] [appbox appstore 1367294518] [appbox appstore 1468791922] [appbox googleplay com.mydaytodo.android.numbersgame] [appbox appstore  1468826652] [appbox appstore  1470834613]
[appbox googleplay com.mydaytodo.simplenotes]
[appbox appstore  1478331765]

Subscribe & never miss a post

If you find any of my posts useful and want to support me, you can buy me a coffee :)

https://www.buymeacoffee.com/bhumansoni

Or you can  buying or even try one of my apps on the App Store. 

https://mydaytodo.com/apps/

In addition the above, have a look at a few of the other posts,
How to create radio buttons using vanilla Javascript
https://mydaytodo.com/vanilla-javascript-create-radio-buttons/

How to build a Javascript frontend for Java Spring Boot backend 
https://mydaytodo.com/java-spring-boot-vanilla-javascript-solution/

Or have a look at some useful Javascript tutorials below
https://mydaytodo.com/category/javascript/

Share this Article
1 Comment

Leave a Reply

Your email address will not be published.

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock