Jonathan
Jonathan

Reputation: 3024

If radio button checked add new form element using dom?

How do I use DOM in Javascript to check if a radio button is checked and then if so add new form elements to datesettings?

//Radio buttons
<input type="radio" id="dateoption" name="dateoption" value="1">
<input type="radio" id="dateoption" name="dateoption" value="2">

//Add new form elements
<span id="datesettings"></span>

Im currently reading a Javascript book but its not helping me understand. If someone could help me with this example then maybe the penny will drop. Thanks for your time.

Upvotes: 1

Views: 3493

Answers (2)

Purge
Purge

Reputation: 647

Check out this page:

It explains the process so you understand why you're doing it a certain way, AND it gives good example code.

http://www.webdevelopersnotes.com/tips/html/finding_the_value_of_a_radio_button.php3

Upvotes: 3

palswim
palswim

Reputation: 12140

You would write a function to do the check, like this:

function CheckDateOptions() {
    var o1 = document.getElementById("dateoption1");
    var o2 = document.getElementById("dateoption2");
    var eSettings = document.getElementById("datesettings");
    if(o1.checked) {
        eSettings.appendChild(...);
    }
    else if(o2.checked) {
        eSettings.appendChild(...);
    }
}

But, you have to make sure to assign your radio buttons unique id values. You can duplicate names to group the radio buttons, but for any element, the id should be unique.

<form id="TestForm">
    <!-- //Radio buttons -->
    <input type="radio" id="dateoption1" name="dateoption" value="1">Text 1</input>
    <input type="radio" id="dateoption2" name="dateoption" value="2">Text 2</text>
    <!-- //Add new form elements -->
    <span id="datesettings"></span>
</form>

Upvotes: 1

Related Questions