簡體   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