tags:

views:

21

answers:

2

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.

+1  A: 

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>
palswim
thanks, makes sense now. :)
Jonny
+3  A: 

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

Alex
You'd also have to make sure that the elements ahd the same name/`form` parent.
palswim
OH, good point! Editting
Alex
thanks :) looks a different way to do it. I cant use this though because i need to add 2 different scenarios to datesettings depending on what radio button is checked. Apparently, innerHTML is not very browser friedly compared to DOM.
Jonny