[英]how to append option to a select
I have a variable which contains a number. 我有一个包含数字的变量。 I'd like to append an option with the numeric value in each based on whatever the variable number is ( ie: if total equals 10, then I need to add 10 options to the select with each option containing the next numeric row value, so 1, 2, 3, 4...etc. I start off with one hard coded option, and then I need to add options dynamically for every case. I've tried a multitude of scripts but I"m getting " cannot use in operator to search for length. 我想根据变量号的不同在每个选项中附加一个数值(即:如果总数等于10,则需要向select添加10个选项,每个选项都包含下一个数字行值,因此1、2、3、4 ...等。我从一个硬编码选项开始,然后我需要针对每种情况动态添加选项。我尝试了多种脚本,但我“无法使用”运算符以搜索长度。
https://jsfiddle.net/v1yyhfm8/ https://jsfiddle.net/v1yyhfm8/
HTML 的HTML
<select id="main">
<option selected>1</option>
</select>
I tried: 我试过了:
var total = dataSource.total();
for (var i = 1; 1 <= total; i++) {
var added = document.createElement('option');
var test = $('#main');
added.value = i;
added.innerHTML = i;
test.append(added);
}
and 和
var total = dataSource.total();
$.each(total, function (i, item) {
$('#main').append($('<option>', {
value: item.total,
text: item.text
}));
});
In your code, the for loop condition would be true always which leads to an infinite loop so change it to i <= total
. 在您的代码中,for循环条件始终为true,这将导致无限循环,因此请将其更改为i <= total
。
var total = dataSource.total();
for (var i = 1; i <= total; i++) {
var added = document.createElement('option');
var select1 = $('#main');
added.value = i;
added.innerHTML = i;
select1.append(added);
}
var total = 10; for (var i = 1; i <= total; i++) { var added = document.createElement('option'); var select1 = $('#main'); added.value = i; added.innerHTML = i; select1.append(added); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="main"> <option selected>1</option> </select>
Html part :
<select id="main">
</select>
Jquery Part:
var opt = ' <option selected>1</option>';
for(var i = 2; i<= 10; i++){
opt += ' <option>' + i + '</option>';
}
$("#main").append(opt);
Jsfiddle link : https://jsfiddle.net/v1yyhfm8/ Jsfiddle链接: https ://jsfiddle.net/v1yyhfm8/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.