In my form, the user is supposed to choose a specific item at the end. As they fill in the initial options, the subsequent fields below change dynamically. Here is an example:
Type:
{
t1:{
Number of X:{
1:{...}
2:{...}
}
Number of Y:{...}
}
t2:{
Number of X:{
100:{...}
200:{...}
}
Number of Y:{...}
}
}
For instance, when the user selects 't1' under Type, the "Number of X" field will display options 1 and 2. If they choose 't2', then the same field will show options 100 and 200. Some choices may depend on more than one field and it's not a straightforward hierarchy.
I initially attempted using event listeners for each field, but soon realized the code was becoming unmanageable with multiple
$("#foo").change(function(){...});
blocks, making it hard to identify which field is listening to a particular event.
Another approach I tried involved JSON (as illustrated above), but this led to repetition as the structure grew deeper, resulting in duplicate fields being defined over and over again. Sometimes choosing 't1' would directly affect an option even if it's not directly related, causing even more repetition in the JSON structure.
How should I tackle this problem? Is there a more readable solution that clearly displays dependencies and their effects? While I'm open to writing more code, clarity and understanding of the relationships are crucial.
An example of my current code:
HTML:
<select id="type">
<option value=1>a</option>
<option value=2>b</option>
</select>
<select id="numOfX">
</select>
<select id="numOfY">
</select>
JavaScript:
$("#type").change(function()
{
if($("#type").val() == 1)
{
$("#numOfX").append(new Option(1, "1", false, false));
$("#numOfX").append(new Option(2, "2", false, false));
}
else if($("#type").val() == 2)
{
$("#numOfX").append(new Option(1, "100", false, false));
$("#numOfX").append(new Option(2, "200", false, false));
}
});
$("#numOfX").change(function()
{
...
});