繁体   English   中英

如何使用selectize js从选择框中获取数据值

[英]How to get the data value from a select box using selectize js

我可以将选项加载到selectize js选择框中。 但是如何从中获取数据值呢? 例如:

$('#product_id').append('<option data-no_of_reams="'+data[i].no_of_reams+'" value="'+data[i].id+'">'+data[i].c_code+'</option>');

我从中获取了值,但是无法从data-no_of_reams="'+data[i].no_of_reams+'". 帮我找到data-no_of_reamsdata-no_of_reams

完整的代码在这里

function getAllCCode(){
$.ajax({
    url: '/inward/allccode/',
    type: 'GET',
    datatype: 'JSON',
    success: function(data){
        $('#product_id').append('<option value="">Select</option>');
        for (var i in data){
            $('#product_id').append('<option data-size="'+data[i].size_h+'X'+data[i].size_w+'" data-radius="'+data[i].radius+'" data-type="'+get_type(data[i].type)+'" data-meal="'+get_mill(data[i].mill)+'" data-variety="'+get_code(data[i].variety)+'" data-ream_weight="'+data[i].ream_weight+'" data-no_of_reams="'+data[i].no_of_reams+'" value="'+data[i].id+'">'+data[i].c_code+'</option>');
        }
    }
}).done(function() {
    $('#product_id').selectize({
        onChange : function(){
            alert('hello');
        }
    });
});

}

提前致谢

您可以使用option data-data对新版本轻松进行此操作。 您可以静态或以编程方式(使用$.ajax )创建option标签。

诀窍是使用this.options selectize内访问该selectize控制权从原建选项。

<select name="product_id" id="product_id">
  <option value="123" data-data="{id:'123',no_of_reams:'1212',name:'Great Expectations'}">Great Expectations Book</option>
  <option value="987" data-data="{id:'987',no_of_reams:'7766',name:'Great Gatsby'}">Great Gatsby Book</option>
</select>

<script>
  $('#product_id').selectize({
   valueField: 'id',
   labelField: 'name',
   render: {
     item: function(item, escape) {
       return '<div>' +
         '<div class="title">' + escape(item.name ? item.name : 'no title') + '</div>' +
         '<div class="description">' + escape(item.description ? item.description : 'no description') + '</div>' +
         '</div>';
     },
     option: function(item, escape) {
       return '<div>' +
         '<div class="title">' + escape(item.name ? item.name : 'no title') + '</div>' +
         '<div class="description">' + escape(item.description ? item.description : 'no description') + '</div>' +
         '</div>';
     }
   },
   onChange: function(val) {
     var data = this.options[val]; // <-- This is how to pull data-data from the original options
     console.log(data); // stores the data-data as a json object
     alert(data.no_of_reams);
   }
  });
</script>

另外,如果您使用PHP进行标记,请确保使用如下所示的htmlentities:

<select name="product_id" id="product_id">
  <option value="123" data-data="<?php echo htmlentities(json_encode(array('id' => 123, 'no_of_reams' => 1212, 'name' => 'Great Expectations'))) ?>">Great Expectations Book</option>
  <option value="987" data-data="<?php echo htmlentities(json_encode(array('id' => 987, 'no_of_reams' => 7766, 'name' => 'Great Gatsby'))) ?>">Great Gatsby Book</option>
</select>

而且,根据selectize文档,当您使用rendervalueField ,您将覆盖默认的<option value="val">name</option> ,因此将从data-data中提取这些内容,而不是从data-data中自动设置这些内容。 <option>上的实际值。 您可以看到此内容,因为即使<option>文本是“ Great Expectations Book” ,它实际上只会显示data-dataname字段-在这种情况下,只是“ Great Expectations”

selectize的问题在于,在构建组合框插件时会复制初始选择选项及其值和标签,但显然会忽略所有其他属性,包括data-*属性。 插件初始化后,基本上不再具有data-attribute的属性,因此您无法读取选择的选项no_of_reams

我附带的解决方法是将数据对象存储在select元素内部数据中,以便以后可以访问它。 这将起作用:

$.ajax({
    url: '/inward/allccode/',
    type: 'GET',
    datatype: 'JSON',
    success: function(data) {
        $('#product_id').append('<option value="">Select</option>').data('data', data);
        for (var i in data) {
            $('#product_id').append('<option value="' + data[i].id + '">' + data[i].c_code + '</option>');
        }
    }
}).done(function() {
    $('#product_id').selectize({
        onChange: function(value) {
            var selectedObj = this.$input.data('data').filter(function(el) {
                return el.id === Number(value);
            })[0];
            alert(selectedObj.no_of_reams)
        }
    });
});

这非常方便:现在在onChange回调中,您已经具有整个selectedObj ,因此您甚至不再需要数据属性。

这是一个演示http : //plnkr.co/edit/pYMdrC8TqOUglNsXFR2v?p=preview

使用此版本,您无需更改HTML。 也可以使用jQuery .data()

 // assuming HTML that looks like: // <select id='mySelect'> // <option val='123' data-myparam='ONE'>My Option 1</option> // <option val='123' data-myparam='TWO'>My Option 2</option> // </select> $(document).ready( function(){ // keep .data (selectize ver 0.12.4 bug / library deletes .data by default) $('#mySelect').selectize({ onInitialize: function(){ var s = this; this.revertSettings.$children.each( function(){ $.extend(s.options[this.value], $(this).data()); }); } }); // Then to read back in: $('#mySelect').on('change', function(){ var s = $('#mySelect')[0].selectize; //get select var data = s.options[s.items[0]]; //get current data() for the active option. alert('your data is: ' + data.myparam); }); }) 
 <link href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.4/css/selectize.default.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.4/js/standalone/selectize.min.js"></script> <select id='mySelect'> <option val='123' data-myparam='ONE'>My Option 1</option> <option val='123' data-myparam='TWO'>My Option 2</option> </select> 

如果仅使用javascript,请使用getAttribute('data-whatever')

如果使用jquery,请使用.data('whatever')

 $(document).ready(function() { var reamsArr = ['34', '44', '55']; $.each(reamsArr, function(index, val) { $('#product_id').append("<option value=" + val + " data-no_of_reams=" + val + ">" + val + "</option>"); }) $("#product_id").on("change", function() { alert($("#product_id option:selected").data("no_of_reams")); }) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select id="product_id"></select> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM