Search code examples
javascripthtmlnode.jsformspolling

Forms in HTML and javaScript


Three radio button options are already there in a form, a radio button option is created on click of a button, on clicking it again a new option is created with the same name. (i)How to stop it behaving similarly over and over again using Javascript? (ii) if not to stop creating, how can we give new options consecutive number as value?

function addOption() {
  var a = document.getElementById('form');
  var x = '<input type="radio" name="poll-option" value="option4" /><label for="option4">';
  var z = '</label><br />';
  var y = 'option' + 4;
  var option = x + y + z;
  a.innerHTML = a.innerHTML + option;
}

we need to change the 'value' attribute in input tag and 'for' attribute in label tag corresponding to the option. for example if I click on button I get new option - option 4 and its attributes value ="option4" and for = "option4". then it will be option 5 for next click.


Solution

  • Try the below code

    var i = 0; //add this global variable, it will be incremented each time it is clicked
    function addOption() { 
            var a=document.getElementById('myForm');       
            var x = '<input type="radio" name="poll-option" value="+i+" /><label for="option4">';
            var z = "</label><br />";
            var y= "option" + i++;
            var option =  x + y + z;
            a.innerHTML += option;
            console.log(a);
        }
    <form id="myForm"></form>
    <button onClick="addOption();">click me</button>
    This works.

    Hope this helps