0

Having trouble getting the a label dynamically assigned to a radio button. all of the code is working except the innerHTML. Cannot spot why. Thanks in advance for any help.

<!DOCTYPE html>
<html>

    <body>
        <form id="myForm">
        </form>
        <br>
        <button onclick="addRadio()">Add radio buttons!</button>

        <script>

            // This function will add a new Radio buttons to the above
            count = 0;
            function addRadio()
            {
                count++;
                //Create input type
                var myRadio = document.createElement("input");
                var myName = document.createElement("testRadio");
                var myBreak = document.createElement("br");
                var myLabel = document.createElement("label");
                var labelMessage = "Radio Button: " + count;
                var labelId = "l" + count;
                myRadio.setAttribute("type", "radio");
                myRadio.setAttribute("name", "testRadio");
                myRadio.setAttribute("value", "Radio Button: " + count);
                myLabel.setAttribute("for", labelId);               
                myRadio.setAttribute("id", labelId);
                document.getElementById('myForm').appendChild(myRadio);
                document.getElementById('myForm').appendChild(myLabel);
                document.getElementById('myForm').appendChild(myBreak);
                document.getElementById('labelId').innerHTML = 'labelMessage';  
            }
            
        </script>
        
    </body>
</html>

2 Answers 2

1

The label element might not be inserted by the next line itself. It is better to do

myLabel.innerHTML = 'labelMessage';

As you have the element already in a variable.

Sign up to request clarification or add additional context in comments.

Comments

0

There is a tiny error in the code.

Before the .innerHTML you get the element by id 'labelId' as a string.

You need to select with the labelID as a var so:

document.querySelector(`label[for="${labelId}"]`).innerHTML = labelMessage;  

2 Comments

Thanks that fixes the error. But doesnt add the label.. if I change myLabel.setAttribute("id", labelId); //myRadio.setAttribute("id", labelId); it adds the label. But then I wonder if the label is then properly associated with the radio button. (sorry cant figure out how to hit enter without submitting the reply)
Yeah I just realised that the id is not set on the label but on the input field. the answer by @boredfromboredom is simpler. juste remove the innerHTML line and add his line after creating the label and the labelMessage and you're good to go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.