Reputation: 191
Can anyone give me demo on how to create dropdown dynamically onchange on another dropdown
I have one dropdown menu in which one can select multiple option like this
<select id='first' multiple='multiple'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
<option value='8'>8</option>
</select>
suppose if user selected first three option from above 1,2 and 3, I am interested to create one more dropdown with single selection like this in one division
<div id='above_selected'>
<select id='first_selected'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>
</div>
As and when there is a change on id='first'
I would like to reflect it on another division
Please someone help me.
Upvotes: 1
Views: 13049
Reputation: 59292
You can do this:
Add <div class="add"></div>
and then do the below
$('#first').change(function () {
if (Number($(this).val()) < 4) {
$('div.add').html("<div id='above_selected'> <select id='first_selected'> <option value='1'>1</option><option value='2'>2</option> <option value='3'>3</option></select></div>");
}
});
Demo: http://jsfiddle.net/AmitJoki/6KfBk/1
Upvotes: -1
Reputation: 27624
$(document).ready(function() {
var dropdown1 = {
1 : ['Four', 'Five', 'Six'],
2 : ['Seven', 'Eight', 'Nine'],
3 : ['Ten', 'Eleven', 'Twelve'],
4 : ['Thirteen', 'Fourteen', 'Fifteen'],
5 : ['Sixteen', 'Seventeen', 'Eighteen']
}
$('#first_selected').html(
'<option>'+dropdown1[1].join('</option><option>')+'</option>'
);
$('#first').on('change',function() {
$('#first_selected').html(
'<option>'+dropdown1[$(this).val()].join('</option><option>')+'</option>'
);
});
});
<select id="first">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
<select id="first_selected">
I think this way is helpful for you to create JavaScript array base on selection array item bind to the another drop down list. Hope this help you!
Upvotes: 1
Reputation: 22567
Here is a very basic demo.
You will need to update this for your own purposes, but this should give you an idea of where to start.
$('#first').change(function(){
var selected = $(this).find("option:selected");
$("#first_selected").append(selected);
});
$('#first_selected').change(function(){
var selected = $(this).find("option:selected");
$("#first").append(selected);
});
Upvotes: 0
Reputation: 208032
Use:
$('#first').change(function () {
$('#above_selected').html("<select id='first_selected'></select>");
for (var i = 0; i < $(this).val().length; i++) {
$('#first_selected').append('<option value="' + $(this).val()[i] + '">' + $(this).val()[i] + '</option>');
}
})
Upvotes: 1