fbpx

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. 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,

Why should we know this?

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

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

Like the blog? Subscribe for updates

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.

Like the blog? Subscribe for updates

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.

‎My Day To-Do - Smart Task List
‎My Day To-Do - Smart Task List
‎AUD $ Currency Converter
‎AUD $ Currency Converter
Developer: Bhuman Soni
Price: $0.99
‎My Day To-Do Lite - Task list
‎My Day To-Do Lite - Task list
‎Snap! I was there
‎Snap! I was there
Developer: Bhuman Soni
Price: Free
Numbers Game: Calculation Master
Numbers Game: Calculation Master
‎Simple 'N' Easy: Todos & food
‎Simple 'N' Easy: Todos & food
‎Captain's Personal Log
‎Captain's Personal Log
Developer: Bhuman Soni
Price: $4.99
My Simple Notes
My Simple Notes
Developer: Bhuman Soni
Price: Free
‎My Simple Notes - Dictate
‎My Simple Notes - Dictate
Developer: Bhuman Soni
Price: $2.99

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *