Populate select box with an array
I have a form containing two radio button, one select box and two arrays.
If I select first radio button then the select box values should be populated with array1
and if radio button 2 is selected then select box should be populated with array2
.
<script type="text/javascript">
var array1=["1","2","3"];
var array2=["4","5","6"];
</script>
<form name="form" id="form">
Radio button 1<input name="btn1" id="a1" type="radio" value="Ra开发者_JAVA技巧dio button 1">
Radio button 2<input name="btn1" id="a2" type="radio" value="Radio button 2" />
<select id="s1" name="myname">
<option selected></option>
</select>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#a1').change(function() {
alert('do array1');
});
$('#a2').change(function() {
alert('do array2');
});
})
</script>
I got the values of radio button, but how I'll populate select box with array values?
jquery
var array1=["1","2","3"];
var array2=["4","5","6"];
var map = { a1 : array1, a2 : array2 };
$('#a1, #a2').change(function() {
$("#s1 option").remove();
$.each(map[this.id], function(i, val) {
var opt = $("<option />");
opt.appendTo($("#s1")).text(val).val(val);
});
});
html
Radio 1<input name="btn1" id="a1" type="radio" value="Radio button 1" />
Radio 2<input name="btn1" id="a2" type="radio" value="Radio button 2" />
<select id="s1" name="myname">
<option selected></option>
</select>
You can try it here.
$(document).ready(function(){
$('input[name=btn1]').change(function(){
var arr = [];
if($(this).attr('id') == 'a1')
arr = array1;
else
arr = array2;
$('select#s1 option').remove();
$.each(arr, function(index, item){
$('select#s1').append('<option value="'+item+'">'+item+'</option>"');
});
});
});
$("#radio_button").change(function(){
$("option","#select_element").remove();
var select_options = $("#select_element").attr("options");
$.each(array,function()
{
select_options[select_options.length] = new Option(this[1],this[0],false,false);
});
});
To keep the values organized and more readable you could use the radio button value property like this...
<input name="btn1" id="a1" type="radio" value="1,2,3" />
<input name="btn1" id="a2" type="radio" value="4,5,6" />
And managing the change as such..
$("[name='btn1']").change(function (e) {
var array = $(this).val().split(",");
$("#s1").empty();
$.each(array, function (index, value) {
$("<option />").appendTo("#s1").text(value).val(value);
});
});
This way you do not end up with variables "floating" around.
精彩评论