For each user, there are several references. Each reference might have different attributes. So I want the user to select the reference attribute first, then for that attribute input fields become visible. If a user has multiple references, he might be able to add a new reference by simply clicking the add button and a new selection appears, and so on.
I tried to do it with javascript but there was some minor problems. I found a rather simple jQuery solution for handling selection:
HTML
<form>
<select id="sel">
<option value="">- select -</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
<input type="text" class="option1" /><span>Textbox label 1</span>
<input type="text" class="option2" /><span>Textbox label 2</span>
<input type="text" class="option2" /><span>Textbox label 2</span>
<input type="text" class="option2" /><span>Textbox label 2</span>
</form>
jQuery
$(function() {
$('#sel').change(function() {
$("input").hide().filter("." + $(this).find("option:selected").val()).show();
});
$("input").focus(function() {
$(this).next("span").fadeIn(1000);
}).blur(function() {
$(this).next("span").fadeOut(1000);
});
});
CSS
input {
display:none;
}
span {
display:none;
}
and then adding new divs..
var inival=1;
function addNew(){
var newArea = add_New_Element();
var htcontents = "<select id="sel">"+
"<option value="">- select -</option>"+
"<option value="option1">Option 1</option>"+
"<option value="option2">Option 2</option>" +
"</select>"+
"<input type="text" class="option1" /><span>Textbox label 1</span>"+
"<input type="text" class="option2" /><span>Textbox label 2</span>"+
"<input type="text" class="option2" /><span>Textbox label 2</span>"+
"<input type="text" class="option2" /><span>Textbox label 2</span>";
document.getElementById(newArea).innerHTML = htcontents;
}
function add_New_Element() {
inival=inival+1;
var ni = document.getElementById('area');
var newdiv = document.createElement('div');
var divIdName = 'Div #'+ inival;
newdiv.setAttribute('id',divIdName);
ni.appendChild(newdiv);
return divIdName;
}
function addNew();
But you might see, this is a very long solution. I guess there is more efficient and shorter solutions. Any help is much appreciated.
Although it is not my solution, it might help other people
http://jsfiddle.net/MXXXT/16/
original answer is belonging to Jeff