Reputation: 2501
Here is the JS Fiddle I am referencing:
http://jsfiddle.net/fiddleyetu/wKbXx/1/
What I would like to ultimately do is modify this to create an array of items associated with a parent category that is dynamically generated. So… for this example, if a user selects:
<li class="list"><input type="checkbox" name="q1" value="Kitchen"/> Kitchen</li>
Then they would get a list of items associated with the Kitchen in a list:
<ul>
<li><a href="#">Cup</a></li>
<li><a href="#">Spoon</a></li>
<li><a href="#">Wine</a></li>
<li><a href="#">Salsa</a></li>
<li><a href="#">Oven</a></li>
</ul>
In the JS Fiddle it looks like I am headed in the right direction with the dynamic population of elements upon a user click, but it turns it into a select dropdown. Any suggestion on how I can make this happen? FYI, the associated items will be pulled from a database array.
Upvotes: 0
Views: 81
Reputation: 56501
Changing the select
to ul
is what you're trying to achieve. I tried to simplify and make it to look consistent like add/remove the exact element based on the checkbox
.
$('input[name=q1]').on('change', function () {
var valu = this.value;
if (this.checked) {
$('#q2').append("<li>" + valu + "</li>");
$('#question2').show();
} else {
var lis = $("#q2").find('li');
lis.each(function () {
if ($(this).text() === valu) {
$(this).remove();
}
});
if (lis.length === 0) {
$('#question2').hide();
}
}
});
Upvotes: 1
Reputation: 175
In your code you are generating <option>
elements and appending them to a <select>
. This will create a drop-down menu.
If you want it to output a list with checkboxes... then you just need to change the HTML that you are inserting in the page.
http://jsfiddle.net/wKbXx/5/
Here I changed it so that instead of a <select>
under question 2, there is a <ul>
, and the jquery code generates and inserts <li>
elements dynamically as you select items in question 1. Is this what you want? Compare this to your original code and you'll see it's basically the same, but with <li>
instead of <option>
.
EDIT:
http://jsfiddle.net/wKbXx/6/
Here is a version with a radio button selection instead of checkbox selection.
Upvotes: 0