如何添加选项以从数组中选择基于框的选项?
我被这个问题困扰了。我想要做的是使用 jquery javascript 在选择框中动态创建选项值。
例如,如果我有一个问题,比如你最喜欢的水果是什么?因此,用户应该能够从默认选择框中选择答案,例如“苹果、橙子、梨、香蕉”。然后,他们可以单击“添加更多水果”,然后将出现第二个选择框,其中包含相同的选择数组。
基本上参考之前另一个成员提出的堆栈溢出问题,我只能把信息拼凑到这里。但是,除了运行时默认的“选择水果”选项之外,我无法从数组中打印出选项值。
$(function() {
// set the array
var fruit = new Array("Apple", "Orange", "Pear", "Banana");
function addFruit() {
$.each(fruit, function(key, value) {
$('#fruit')
.append($('<option>', { value : key })
.text(value));
});
}
var i = $("li").size() + 1;
$("a#addmore").click(function() {
$("#addmore_row").append('<li>' +
'<select name="fruit[]" id="fruit">' +
'<option value="">Select Fruit:</option>' +
addFruit()
+ '</select>' +
'</li>');
return false;
});
});
有人可以帮我解决这个问题吗?非常感谢。
I am stuck with this issue. What I want to do is to create the option values in a select box on the fly with the use of jquery javascript.
For example, if I have a question like what are your favourite fruits? So users should be able to select an answer from the default select box e.g. "Apple, Orange, Pear, Banana". Then they can click on a click "Add more fruits" and a second select box will appear with the same array of selection.
Basically with reference to the previous stack overflow question from another member, I could only piece up the information till here. But I could not have the option values printed out from the array, aside from the default "Select Fruit" option, at runtime.
$(function() {
// set the array
var fruit = new Array("Apple", "Orange", "Pear", "Banana");
function addFruit() {
$.each(fruit, function(key, value) {
$('#fruit')
.append($('<option>', { value : key })
.text(value));
});
}
var i = $("li").size() + 1;
$("a#addmore").click(function() {
$("#addmore_row").append('<li>' +
'<select name="fruit[]" id="fruit">' +
'<option value="">Select Fruit:</option>' +
addFruit()
+ '</select>' +
'</li>');
return false;
});
});
Can anyone please help me out with this? Thank you very much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
addFruit
在构建表示select
的字符串时被调用。由于它仍在构造要附加的字符串,因此select
实际上还不存在,但仍会调用addFruit
。简而言之,将addFruit
从字符串连接中移出,放在附加select
之后。换句话说,这个:
addFruit
is being called while it's constructing the string representing theselect
. Since it's still constructing the string to append, theselect
doesn't actually exist yet, butaddFruit
is still being called. In short, moveaddFruit
out of the string concatenation to after you've appended theselect
.In other words, this: