Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 18, 2023 › #append #dynamically

How to create radio button dynamically using JavaScript

In this article, you are going to learn how to create a radio button dynamically using JavaScript.

To dynamically create a radio button, you need to call the createElement() method.

The following example will create a radio button with its necessary attributes.

 let newVar = document.createElement('input');
     newVar.type = 'radio';
     newVar.id = 'radio-btn';
     newVar.checked = false;
 document.querySelector('.container').appendChild(newVar);
  1. In the above example, we have created an input element using the createElement() method and stored in a variable named newVar.
    let newVar = document.createElement('input');
  2. Then, we have set its type to radio using the JavaScript type property and we also added an id using the id property.
    let newVar = document.createElement('input');
        newVar.type = 'radio';
        newVar.id = 'radio-btn';
  3. Using the checked property, we can specify whether a checkbox should be checked or not.
    true - The checkbox is checked.
    false - The checkbox is not checked (default).
    let newVar = document.createElement('input');
        newVar.type = 'radio';
        newVar.id = 'radio-btn';
        newVar.checked = false; 
  4. Now you can display the created radio button element where you want it to display using the appendChild() method.
    let newVar = document.createElement('input');
        newVar.type = 'radio';
        newVar.id = 'radio-btn';
        newVar.checked = false;
        document.querySelector('.container').appendChild(newVar);
save
listen
AI Answer
1 Answer
Write Your Answer
  1. Create radio button on button click.
    const radioBtn = document.createElement('input');
               radioBtn.type = 'radio';
    document.body.appendChild(radioBtn);


    https://www.3schools.in/p/code-editor.html?q=PGRpdiBjbGFzcz0iY29udGFpbmVyIj48L2Rpdj4KPGJ1dHRvbiBvbmNsaWNrPSJteUZ1bmN0aW9uKCkiPgogIENyZWF0ZSBhIHJhZGlvIGJ1dHRvbgo8L2J1dHRvbj4KPHNjcmlwdD4KZnVuY3Rpb24gbXlGdW5jdGlvbigpewogIGxldCBuZXdWYXIgPSBkb2N1bWVudC5jcmVhdGVFbGVtZW50KCdpbnB1dCcpOwogIG5ld1Zhci50eXBlID0gJ3JhZGlvJzsKICBuZXdWYXIuaWQgPSAncmFkaW8tYnRuJzsKICBuZXdWYXIuY2hlY2tlZCA9IGZhbHNlOwogIGRvY3VtZW50LnF1ZXJ5U2VsZWN0b3IoJy5jb250YWluZXInKS5hcHBlbmRDaGlsZChuZXdWYXIpOwp9Cjwvc2NyaXB0Pg==
    Reply Delete
    Share
loading
back
View All