0

我正在制作一个自定义多选选项框,我需要将一组选定值传递给元素

var data=[];
$(".opt > div").click(function(){
  data[data.length]=$(this).attr("value");
  $(".options").val(data);  // putting data into custom option
});

HTML

<div class="wrapper"> <!-- own custom style -->
  <select class="options"> <!-- select is hidden with CSS -->
    <!-- options -->
  </select>
</div>

<div class="opt"> <!-- this div is dynamically created by clicking         no class wrapper and populated the inside with select box's options with jQuery -->
  <div value="0">item 1</div>
  <div value="1">item 2</div> 
  <div value="2">item 3</div> 
</div>

一切进展顺利但是在点击事件中,我想用数组“数据”来评估 .option 类,并通过它作为请求提交时的表单传递它。如何将数组(数据)设置为它的值?

就像在复选框中一样,给出 name ="somename[]"这样的名称会使响应成为一个数组。或者一个

上面的代码只是我想要的一个简短的演示

4

3 回答 3

1

First, make your select multi and give it a name:

<select name="cmbSomeName" class="options" multiple="multiple">

Second, on the click, reset your select options and reselect select all that are in the data array.

var data=[];
$(".opt > div").click(function(){
   data[data.length]=$(this).attr('value');

   //Unselect all the options
   $('.options option').each(function(){ this.selected = false; })

   //For each item in data, select the respective option in the select
   $.each(data, function(){
      $('.options options[value="' + this + '"]').prop('selected', true);
   });
});

Finally, when you submits your form, the cmbSomeName will be an array in the server side

Its important to note that this code will always increase the data[] array, so, you will not be enable to "unselect" those itens, for such, I would do diferent coding like so:

 $(".opt > div").click(function(){
      jqOption = $('.options options[value="' + $(this).attr('value') + '"]');

      //Toggle (if true then false else true)
      jqOption.prop('selected', !jqOption.prop('selected'));
 })
于 2013-08-28T12:45:15.910 回答
0

利用,

$(".options").append(data); 

不要使用值来编写 html

于 2013-08-28T12:19:23.027 回答
0

演示

诀窍是:

  • 克隆选择options
  • 把它们放在一个DIV(好吧,谁在乎,它工作得很好)
  • 在 DIV 单击上定位原始 Select 元素:

<div class="wrapper"> <!-- note! it wraps the select and the .opt -->
  <select class="options" multiple>
    <option value="0">Item 1</option>
    <option value="1">Item 2</option>
    <option value="2">Item 3</option>
  </select>
  <div class="opt"></div> <!-- will be populated by jQ -->
</div>

$('.options').each(function(){ 
  $(this).next('.opt').html($(this).html());
});

$('.opt').on('click', 'option', function(){
  $(this).toggleClass('selected')
         .parent().prev('select')
         .find('option[value='+ this.value +']')[0].selected ^= 1;
});

使用这个基本的 CSS:

.opt option{
  background:#eee;
  border-bottom:1px solid #888;
  cursor:pointer;
}
.opt option:hover{
  background:#ddd;
}
.opt option.selected{
  background:#cf5;
}
于 2013-08-28T12:26:11.377 回答