Kallol Pratim
Kallol Pratim

Reputation: 51

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

I am able load the options to a selectize js select box. But how can I get the data-value from it? For example:

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

I get the the value from it but unable to get the data from data-no_of_reams="'+data[i].no_of_reams+'". Help me to find the data of data-no_of_reams

The full code here

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');
        }
    });
});

}

Thanks in advance

Upvotes: 5

Views: 11959

Answers (4)

user3638793
user3638793

Reputation: 61

With this version you won't have to change your HTML. Works with jQuery .data() as well

// 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>

Upvotes: 4

redheadedstep
redheadedstep

Reputation: 333

You can easily do this with the new version using data-data within the option. You can create the option tag either statically or programmatically (using $.ajax).

The trick is to use the this.options within selectize to access the original options that the selectize control was built from.

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

Also, if you are using PHP to do the markup, make sure you use htmlentities like so:

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

And, per the selectize documentation, when you use render and valueField, you are overwriting the default <option value="val">name</option>, so those are pulled from the data-data instead of being auto-set from the actual value on the <option>. You can see this because even though the <option> text is Great Expectations Book, it will actually just display the name field from data-data - in this case just Great Expectations

Upvotes: 15

dfsq
dfsq

Reputation: 193301

The problem with selectize is that when building combobox plugin copies initial select options with their values and labels, but apparently it ignores all other attributes, including data-* ones. After plugin is initializes there are basically no data- attributes anymore, so you can't read selected option no_of_reams.

The workaround I came with is to store data object in select element internal data so you can access it later. This will work:

$.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)
        }
    });
});

It's pretty convenient: now in onChange callback you have entire selectedObj, so you don't even need data-attributes anymore.

Here is a demo: http://plnkr.co/edit/pYMdrC8TqOUglNsXFR2v?p=preview

Upvotes: 1

roshan
roshan

Reputation: 2510

Use getAttribute('data-whatever') if only javascript.

Use .data('whatever') if using jquery.

$(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>

Upvotes: -1

Related Questions