2013-04-13 61 views
0

如果用户输入一个值(通过javascript提示),并且该值存储在不断变化的数组中,是否有方法自动更新select在HTML表单中输入用户输入的值?我问,因为我对jquery和前端设计相当陌生,而且我不确定这是否可以在加载页面后完成。根据用户提示动态填充选择框(jQuery/javascript)

我很感激来自两位回复的人的帮助,我会赞成你的回答有帮助,但我还没有足够的声望。

为了更清楚地说明我的问题,我希望看到的是根据用户提示自动填充值的选择框。

举例来说,如果我有

var r = true; 
while(r == true){ 
var path = window.prompt("Please enter path here"); 
//I would like to put <option>path</option> inside a selection box 
var r = confirm("Enter another path?"); 
} 

如果这不是完全可能的,我明白了,但是这就是为什么我问的问题摆在首位。

编辑:

在这里找到 How to add option to select list in jQuery

+0

嗯,我是投票,因为我喜欢挑战。我认为这是一个有用的问题和资源(尽管显然,这至少是部分地受到自我利益的驱使)。 –

回答

0

类似下面的解决方案应该工作。这样会覆盖现有的选项,但可以将它们附加到现有的选项上。

$("#saveButton").on("click", function(){ 
    var options = ''; 

    for (var item in optionsArray){ 
     options += "<option>" + item +"</option>"; 
    }  

    $('#selectbox').html(options) 
}); 

小提琴:http://jsfiddle.net/njgray/BM8KL/

1

所以,我得到了一小会儿那种无聊;既然如此,我可以给你这个:

var startValues = ['apple', 'banana', 'cherry']; 

function childElementType(node) { 
    var props = { 
     childType: '', 
     textType: Node.textContent ? 'textContent' : 'innerText', 
     hasValue: false 
    }; 
    switch (node.tagName.toLowerCase()) { 
     case 'select': 
      props.childType = 'option'; 
      props.hasValue = true; 
      break; 
     case 'ol': 
     case 'ul': 
      props.childType = 'li'; 
      break; 
    } 
    return props; 
} 
Object.prototype.populate = function (values) { 
    if (this.length) { 
     return this; 
    } else { 
     var child = childElementType(this), 
      newChild; 
     for (var i = 0, len = values.length; i < len; i++) { 
      newChild = document.createElement(child.childType); 
      newChild[child.textType] = values[i]; 
      if (child.hasValue) { 
       newChild.value = newChild[child.textType]; 
      } 
      this.appendChild(newChild); 
     } 
    } 
    return this; 
}; 

Object.prototype.addTo = function (message) { 
    var control = document.createElement('button'), 
     that = this; 
    control.appendChild(document.createTextNode(message || '+ add to ' + that.tagName.toLowerCase())); 
    this.parentNode.insertBefore(control, this.nextSibling); 
    var child = childElementType(this); 

    function addNew() { 
     var text = prompt('Add the new entry:'), 
      newEntry; 
     if (text) { 
      newEntry = document.createElement(child.childType); 
      newEntry[child.textType] = text; 
      that.appendChild(newEntry); 
     } 
    } 
    control.onclick = addNew; 
    return this; 
}; 

document.getElementById('select').populate(startValues).addTo(); 
document.getElementById('ul').populate(startValues).addTo(); 

JS Fiddle demo

您也可以在传递一个默认的消息给addTo()方法,给出具体的文字所创建的按钮和,因为每个方法返回this对象/节点,你可以打电话给他们以任何顺序(只要显然中,选择的元素第一),例如两者,这些方法是有效的和可用的:

document.getElementById('select').addTo('Moar options..?').populate(startValues); 
document.getElementById('ul').populate(startValues).addTo('Go on, add more!'); 

JS Fiddle demo

参考文献: