I am trying to do the following with an HTML form and some JavaScript:
A checkbox that when checked generates two radio buttons dynamically and a text that says “Checkbox 1 is checked”.
The logic (seen in jsFiddle: http://jsfiddle.net/9jPcP/) does work, but for some reason, the two radio buttons can’t be selected. When I click on either radio button nothing happens. I’d appreciate it if any of you guys have some input on what I might be doing wrong.
Note: The sequence doesn’t seem to work (radio buttons are indeed generated dynamically) on jsFiddle but it does work on my workstation.
HTML code:
<form name="input" action="" method="get">
<input type="checkbox" name="sequenceOP" id="sequenceOP14" onChange="displaySequence()">
Checkbox 1<br/>
<div id="displayText"></div>
<div id="variableSpdExhOptions"></div>
</form>
JavaScript:
function displaySequence(){
var displayVariableExhOptions = "";
var displayText = "";
if(sequenceOP14.checked){
displayText += "Checkbox 1 is checked";
displayVariableExhOptions += "<input type=\"radio\" name=\"exhOptions\" id=\"sequenceOP15\" onChange=\"displaySequence()\" >"
+ "Radio Box 1<br/>"
+ "<input type=\"radio\" name=\"exhOptions\" id=\"sequenceOP16\" onChange=\"displaySequence()\" >"
+ "Radio Box 2<br/>"
}
document.getElementById("variableSpdExhOptions").innerHTML = displayVariableExhOptions;
document.getElementById("displayText").innerHTML = displayText;
}
Here is is the fix for your issue: Fix JS Fiddle.
Basically what was wrong is your JS was been loaded on domReady and then discard.
You want it to be loaded in the head.
Code Here:
<head>
<script type="text/javascript">
//<![CDATA[
function ds() {
var displayVariableExhOptions = "";
var displayText = "";
if (document.input.sequenceOP14.checked) {
displayText += "Checkbox 1 is checked";
displayVariableExhOptions += "<input type=\"radio\" name=\"exhOptions\" id=\"sequenceOP15\" onChange=\"displaySequence()\" >" + "Radio Box 1<br/>" + "<input type=\"radio\" name=\"exhOptions\" id=\"sequenceOP16\" onChange=\"displaySequence()\" >" + "Radio Box 2<br/>"
}
document.getElementById("variableSpdExhOptions").innerHTML = displayVariableExhOptions;
document.getElementById("displayText").innerHTML = displayText;
}
</script>
</head>
<form name="input" action="" method="get">
<input type="checkbox" name="sequenceOP" id="sequenceOP14" onChange="ds();">
Checkbox 1<br/>
<div id="displayText"></div>
<div id="variableSpdExhOptions"></div>
</form>
To save you worrying about ids make it a bit easier for yourself:
<input type="checkbox" name="sequenceOP" id="sequenceOP14" onChange="ds(this);">
function ds(obj) {
var displayVariableExhOptions = "";
var displayText = "";
if (obj.checked) {