jquery-ui组合框从菜单项创建数组



我正在取消此版本的组合框。。。combobox

我正在尝试获取菜单项,然后创建一个json数组,这是我迄今为止得到的代码。。。

"keyup .ui-combobox-input":function(event){
    if(event.keyCode==13){
            event.preventDefault();
            newItem=$(this.uiInput).val()
            this.element.append('<option value="'+newItem+'">'+newItem+'</option>');
            var text=JSON.stringify(this.element.text());
    };
}

我从var文本中得到的输出是。。。

"ntttttttttttone moretwothreefour" 

但我想要这个。。。

[{"value":"1", "label":"one more"}, {"value":"2", "label":"two"}, {"value":"3", "label":"three"}, {"value":"4", "label":"four"}]

我不知道转义的n和t是什么,当我尝试使用此text=$.parseJSON(text);将文本转换为数组时,文本不会转换为数组。

我不完全确定您的代码,因为有多个对该属性的引用。但据我所知,你能做的如下。

1) 选择列表/组合框

       <div class="ui-widget" id="test">
         <label>Your preferred programming language: </label>
           <select id="combobox">
             <option value="ActionScript">ActionScript</option>
             <option value="AppleScript">AppleScript</option>
           </select>
       </div>

2) 组合框的键控事件

    $(".ui-combobox-input").keyup(function(event){
        if(event.keyCode==13){
                event.preventDefault();
              //This gives the value being entered in text field on dropdown 
                var textVal = $(".ui-combobox-input").val();
              //var dd = $('#combobox').val();  
              //this.element.append('<option value="'+newItem+'">'+newItem+'</option>'); **THIS did not work for me**
                var combobox = []
                $('#combobox').append($('<option>', {value:textVal, text:textVal, selected:true})); //USE SELECTED:TRUE if you want dynamically added value to be selected Please TEST it if its getting selected or not
                $('#combobox > option').each(function() {
                   combobox.push(
                      {
                         value: $(this).val(), 
                         label: $(this).text()
                      })
                   });
                jsonString = JSON.stringify(combobox);
                alert(jsonString);
        };
    });
 });

您可以对上述代码进行的其他改进是使用ID for DIV来保持下拉列表,并更新该元素的相关keyup。(如果您在同一页面上有多个这样的元素)。对元素使用唯一有意义的名称。我刚刚在上面的代码中使用了随机名称。我希望它能有所帮助。

我不知道你到底想做什么,但你可以用JQuery来做。您可以遍历一个选择列表项并创建一个JSON对象。

var combobox = []
$('select option').each(function() {
   combobox.push(
      {
         value: $(this).val(), 
         label: $(this).text()
      })
   });
jsonString = JSON.stringify(combobox);
alert(jsonString);

这将打印出:[{"value":"1","label":"one"},{"value":"2","label":"two"}]

希望这能有所帮助!

以下是一个JSFiddle:https://jsfiddle.net/sm6w19cq/

最新更新