Dynamically populating Select options with jQuery - javascript

I'm looking for a better way to handle dynamic populating of my options using JS and JQuery. What I have is working but I am looking for a way to not have t ore-write the function each time I need to populate a list.
Fiddle
And what I am doing is populating these:
<label for="recordPurchaseTimeFrameID" class="input required">When would you like to move?</label>
<select name="recordPurchaseTimeFrameID" id="recordPurchaseTimeFrameID" class="inputclass pageRequired" title="Select a Time Frame">
<label for="recordPurchasePriceRangeID" class="input required">Purchase price range:</label>
<select name="recordPurchasePriceRangeID" id="recordPurchasePriceRangeID" class="inputclass pageRequired" title="Select a Price Range">
Using these scripts:
var rPTJsonListItems= "";
for (var i = 0; i < rPTJsonList.recordPurchaseTimeTable.length; i++){
rPTJsonListItems+= "<option value='" + rPTJsonList.recordPurchaseTimeTable[i].recordPurchaseTimeValue + "'>" + rPTJsonList.recordPurchaseTimeTable[i].recordPurchaseTimeAmount + "</option>";
};
$("#recordPurchaseTimeFrameID").html(rPTJsonListItems);
var rPPJsonListItems= "";
for (var i = 0; i < rPPJsonList.recordPurchasePriceTable.length; i++){
rPPJsonListItems+= "<option value='" + rPPJsonList.recordPurchasePriceTable[i].recordPurchasePriceValue + "'>" + rPPJsonList.recordPurchasePriceTable[i].recordPurchasePriceAmount + "</option>";
};
$("#recordPurchasePriceRangeID").html(rPPJsonListItems);
And using this to populate the dropdowns:
var rPTJsonList = {
"recordPurchaseTimeTable" :
[
{"recordPurchaseTimeValue" : "","recordPurchaseTimeAmount" : "Select"},
....
]};
var rPPJsonList = {
"recordPurchasePriceTable" :
[
{"recordPurchasePriceValue" : "","recordPurchasePriceAmount" : "Select"},
{"recordPurchasePriceValue" : "75k-100k","recordPurchasePriceAmount" : "$75,000 - $100,000"},
....
});
So what I'd like is to have just one main function that populates each unique ID based on it's correlating JSON.
Anyone have any suggestions?

I would suggest you simplify your data as a collection, instead of nested objects, that way you can abstract more easily:
var timeTable = [{
"recordPurchaseTimeValue": "",
"recordPurchaseTimeAmount": "Select"
}, {
"recordPurchaseTimeValue": "3-6",
"recordPurchaseTimeAmount": "3-6 months"
}, {
"recordPurchaseTimeValue": "6-9",
"recordPurchaseTimeAmount": "6-9 months"
}, {
"recordPurchaseTimeValue": "9-12",
"recordPurchaseTimeAmount": "9-12 months"
}, {
"recordPurchaseTimeValue": "12",
"recordPurchaseTimeAmount": "Over 12 months"
}];
var priceTable = [{
"recordPurchasePriceValue": "",
"recordPurchasePriceAmount": "Select"
}, {
"recordPurchasePriceValue": "75k-100k",
"recordPurchasePriceAmount": "$75,000 - $100,000"
}, {
"recordPurchasePriceValue": "100k-125k",
"recordPurchasePriceAmount": "$100,000 - $125,000"
}, {
"recordPurchasePriceValue": "125k-150k",
"recordPurchasePriceAmount": "$125,000 - $150,000"
}, {
"recordPurchasePriceValue": "150k-200k",
"recordPurchasePriceAmount": "$150,000 - $200,000"
}, {
"recordPurchasePriceValue": "200k-250k",
"recordPurchasePriceAmount": "$200,000 - $250,000"
}, {
"recordPurchasePriceValue": "250k-300k",
"recordPurchasePriceAmount": "$250,000 - $300,000"
}, {
"recordPurchasePriceValue": "300k-350k",
"recordPurchasePriceAmount": "$300,000 - $350,000"
}, {
"recordPurchasePriceValue": "350k-400k",
"recordPurchasePriceAmount": "$350,000 - $400,000"
}, {
"recordPurchasePriceValue": "400k-500k",
"recordPurchasePriceAmount": "$400,000 - $500,000"
}, {
"recordPurchasePriceValue": "500k-700k",
"recordPurchasePriceAmount": "$500,000 - $700,000"
}, {
"recordPurchasePriceValue": "700k-900k",
"recordPurchasePriceAmount": "$700,000 - $900,000"
}, {
"recordPurchasePriceValue": "900k",
"recordPurchasePriceAmount": "$900,000"
}];
Then you can create a function to populate selects given the data as a collection, and the attributes to set on each generated option, that map to a given key.
We can use document fragments to improve performance, as you only need to append to the DOM once.
Demo: http://jsfiddle.net/Ls4mD/
function populateSelect(select, data, attrs) {
var frag = document.createDocumentFragment();
data.forEach(function(option) {
var opt = document.createElement('option');
for (var i in attrs) {
opt[i] = option[attrs[i]];
}
frag.appendChild(opt);
});
select.appendChild(frag.cloneNode(true));
}
var time = document.getElementById('recordPurchaseTimeFrameID');
var price = document.getElementById('recordPurchasePriceRangeID');
populateSelect(time, timeTable, {
value: 'recordPurchaseTimeValue',
textContent: 'recordPurchaseTimeAmount'
});
populateSelect(price, priceTable, {
value: 'recordPurchasePriceValue',
textContent: 'recordPurchasePriceAmount'
});

Related

What is the best way to extract all rows from Datatables under a criteria in Javascript

I'm currently working on a condominum program. The goal of this issue is when one Apartment row is clicked on the Parent table all the months - related to that apartment - must be displayed on the Child table.
The click/select/deselect is working fine but I can not obtain all the twelfth months.
This is my actual tables layout (example 1):
And this is my actual tables layout (example 2):
My code to childTable is:
var childTable = $('#child').DataTable( {
"pageLength": 12,
ajax: {
url: "ajax/query_pagquotas.php", // This is the URL to the server script for the child data
dataSrc: function (data) {
var selected = parentTable.row( { selected: true } );
if ( selected.any() ) {
var ID = selected.data().ID;
for (var i=0; i < data.data.length; i++) {
var rows = data.data[i];
if (rows.ID === ID) {
return [rows];
}
}
} else {
return [];
}
}
},
columns: [
{ "data": "ID" },
{ "data": "DATA" },
{ "data": "MES" },
{ "data": "VALOR" },
{ "data": "METODO" },
{ "data": "ESTADO" },
{ "data": "OBS" }
]
} );
Thanks for your help Masters
[edited]
Ups! If condition at the end does not make the 'deselect' work...
This is my full code at the moment:
$(document).ready(function() {
var parentTable = $('#parent').DataTable( {
ajax: "ajax/dbfraccoes.php",
"language": {
"sSearchPlaceholder": "Apto ou Proprietário...",
"url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Portuguese.json",
},
"processing": true,
"scrollY": "200px",
"scrollCollapse": true,
"paging": false,
pageLength: 5,
select: {
style: 'single'
},
columns: [
{ "data": "ID","searchable": false },
{ "data": "APTO" },
{ "data": "FRACCAO"},
{ "data": "PROPRIETARIO" },
{ "data": "VALOR_QUOTA","searchable": false, className: "cssValores"},
{ "data": "OBS" }
]
} );
// tabela Child ------------------------------------------
var childTable = $('#child').DataTable( {
columnDefs: [{
targets: 6,
render: function(data, type, row, meta){
if(type === 'display' && data === 'EMITIDO'){
data = '<td style="text-align:center"><button type="button" class="btn btn-info btn-sm cssButton center" title="Emitido Aviso de Recibo a pagamento">EMITIDO</button></td>'+
'<div class="links">' +
'Editar ' +
'</div>';
}else if (type === 'display' && data === 'AGUARDA'){
data = '<td style="text-align:center"><button type="button" class="btn btn-warning btn-sm cssButton center" title="Limite de pagamento ultrapassado. Em período de tolerância.">AGUARDA</button></td>'+
'<div class="links">' +
'<a href="<?php echo WEB_URL;?>credit_debit/gest_quotas.php?spid='+
row['pqid']+'#insert">Editar</a> ' +
'</div>';
}
return data;
}
}],
"paging": false,
"searching": false,
"language": {
"zeroRecords": "<center>Clique na tabela acima, na linha do apartamento que pretende. <br/>Os dados da fracção/apartamento selecionado acima serão reflectidos nesta tabela</center>",
},
ajax: {
url: "ajax/query_pagquotas.php",
dataSrc: function (data) {
var selected = parentTable.row( { selected: true } );
if ( selected.any() ) {
var rows = []; // create an empty array
var ID = selected.data().ID;
for (var i=0; i < data.data.length; i++) {
var row = data.data[i];
if (row.ID === ID) {
rows.push(row);
}
}
}
return rows;
},
},
columns: [
{ "data": "pqid" },
{ "data": "ID"},
{ "data": "DATA" },
{ "data": "MES"},
{ "data": "VALOR", className: "cssValores"},
{ "data": "METODO" },
{ "data": "ESTADO" },
{ "data": "OBS" }
]
} );
// This will load the child table with the corresponding data
parentTable.on( 'select', function () {
childTable.ajax.reload();
} );
//clear the child table
parentTable.on( 'deselect', function () {
childTable.ajax.reload();
} );
} );
The simplest way to adjust your existing code, is to change the logic in your dataSrc: function (data) {...}.
At the moment, you are only creating an array of one item.
So, instead you can do this:
dataSrc: function (data) {
var selected = parentTable.row( { selected: true } );
var rows = []; // create an empty array
if ( selected.any() ) {
var ID = selected.data().ID;
for (var i=0; i < data.data.length; i++) {
var row = data.data[i]; // change the variable name to "row"
if (row.ID === ID) {
rows.push(row); // add the new row to your array of rows
}
}
}
return rows; // return your array of rows
}
The most important line here is: rows.push(row); which is how JavaScript adds a new item to the end of an array.
So, now at the end of your dataSrc function you will either have an empty array [] if no rows were selected, or you will have an array of rows which match your ID.
That should solve your current problem.
The above approach should work - but it involves fetching every child row, every time - and then filtering out the ones you do not want to show.
You can probably improve on this by submitting the ID of the selected row as part of the child table's ajax URL. You can move the relevant code from its current location into your parentTable's on(select) function:
var selectedID = -1
parentTable.on( 'select', function () {
var selected = parentTable.row( { selected: true } );
if ( selected.any() ) {
selectedID = selected.data().ID;
}
childTable.ajax.reload();
} );
I do not know how you have implemented your ajax/query_pagquotas.php, so I am not sure of the best way to pass the selectedID parameter to it.
Normally I would append it as a query parameter in your ajax parameters:
data: 'id=' + selectedID
You may already know how to do this yourself.
Once you have passed the selectedID to your PHP, then you can use it to return only the records you want to display - and you can remove all of the existing dataSrc: function (data) {...} logic from your child table definition.

How to enable/disable 2nd dropdownlist value based on the selection of the previous dropdown value

We have 2 dropdowns. On selection of the first dropdown the value related to it show be enabled or get highlighted and rest other options should be in disabled in the second dropdown. Both the dropdowns are multiselect and are array of objects.
I am able to append the conditional value in the second dropdown but rest other options are getting hide.I want all options to be visible and teh one selcted should be enabled/highlighted.
var firstVal = [
{ id: 1, value: 'foo1' },
{ id: 2, value: 'foo2' },
{ id: 3, value: 'foo3' },
]
var secondVal = [
{ id: 1, value: 'foo11' },
{ id: 2, value: 'foo21' },
{ id: 2, value: 'foo22' },
{ id: 3, value: 'foo31' },
{ id: 3, value: 'foo32' },
]
$('#rewardType').change(function (){
var firstSelcted = $(this).val();if (firstSelcted && firstSelcted.length > 0) {
for (var j = 0; j < firstSelcted.length; j++) {
var filtered = secondVal.filter( function(myArr){
return myArr.id == firstSelcted[j];
});for (var k = 0; k < filtered.length; k++) {
$('#rewardTypes').append('<option value="' + filtered[k].value + '">' + filtered[k].value + '</option>');
}
$('this').css('background-color','red');
$('#rewardTypes').selectpicker('refresh');
}
If I select foo2 in first dropdown then in 2nd dropdown it should get highlighted or enabled foo21,foo22. And rest others should be disabled.
You can try below approach where you can populate list using json array and on change event of first list you can enable or disable the second list options
$(document).ready(function(){
var firstVal = [
{ id: 1, value: 'foo1' },
{ id: 2, value: 'foo2' },
{ id: 3, value: 'foo3' },
] ;
var secondVal = [
{ id: 1, value: 'foo11' },
{ id: 2, value: 'foo21' },
{ id: 2, value: 'foo22' },
{ id: 3, value: 'foo31' },
{ id: 3, value: 'foo32' },
]
var $firstList = $('#rewardType');
var $secondList = $('#rewardTypes');
$.each(firstVal, function(key,val){
$firstList.append('<option value="' + val.id + '">' + val.value + '</option>');
});
$.each(secondVal, function(key,val){
$secondList.append('<option disabled value="' + val.id + '">' + val.value + '</option>');
});
$firstList.change(function(){
var value = $(this).val();
//console.log(value);
$secondList.val("");
$secondList.find('option').each(function(){
var optVal = $(this).attr('value');
//console.log("option " + optVal);
if(value.indexOf(optVal)>=0) {
$(this).removeAttr('disabled');
} else {
$(this).attr('disabled',true);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<select id="rewardType" multiple="true"><option value=""></option></select>
<select id="rewardTypes" multiple="true"><option value=""></option></select>
First code block is for HTML and second code block is JQuery
try this:
<select id='firstval' onchange="witness();">
<option selected></option>
<option value="1">Apple</option>
<option value="2">Mango</option>
</select>
<select id='secondval'>
<option selected></option>
<option value="1">Apple</option>
<option value="2">Mango</option>
</select>
function witness(){
$("#secondval option").each(function(){
if($("#firstval option:selected").val() == $(this).val())
$(this).attr("disabled", "disabled");
else
$(this).removeAttr("disabled");
});
}

How append a json data in select box with optgroup

I am a newbie in jquery. I want to display JSON data to my select box. My JSON Data is
{
"Color":[
{
"Id":"1",
"Attrib_name":"Color",
"Attrib_value":"Red"
},
{
"Id":"2",
"Attrib_name":"Color",
"Attrib_value":"Blue"
}
],
"Size":[
{
"Id":"3",
"Attrib_name":"Size",
"Attrib_value":"5.6"
},
{
"Id":"4",
"Attrib_name":"Size",
"Attrib_value":"5.1"
}
]
}
I want to create optgroup with option based on the above json. i.e
<optgroup label="color">
<option>Red</option>
<option>Blue</option>
</optgroup>
<optgroup label="size">
<option>5.6</option>
<option>5.1</option>
</optgroup>
I am stuck on how to start. Please help me to get rid of this.
Just take the result of this code and paste it as HTML
What it does is iterate over your json object and create the elements.
var json = {
"Color":[
{
"Id":"1",
"Attrib_name":"Color",
"Attrib_value":"Red"
},
{
"Id":"2",
"Attrib_name":"Color",
"Attrib_value":"Blue"
}
],
"Size":[
{
"Id":"3",
"Attrib_name":"Size",
"Attrib_value":"5.6"
},
{
"Id":"4",
"Attrib_name":"Size",
"Attrib_value":"5.1"
}
]
}
console.log(
Object.keys(json).map(a=>`<optgroup label="${a}">${json[a].map(b=>`<option>${b.Attrib_value}</option>`).join``}</optgroup>`)
)
Here is a full example of how you can do this. You just have to build your HTML and use a jQuery function to add it in the html file. Check my codepen. Code is also bellow
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"
type="text/javascript"></script>
<select id="mySelect"></select>
<script type="text/javascript">
var data = {
"Color":[
{
"Id":"1",
"Attrib_name":"Color",
"Attrib_value":"Red"
},
{
"Id":"2",
"Attrib_name":"Color",
"Attrib_value":"Blue"
}
],
"Size":[
{
"Id":"3",
"Attrib_name":"Size",
"Attrib_value":"5.6"
},
{
"Id":"4",
"Attrib_name":"Size",
"Attrib_value":"5.1"
}
]
};
var html = "";
for(var option in data){
html += `<optgroup label="`+ option +`">`;
data[option].forEach(function(item){
html += `<option value="` + item["Attrib_value"] + `" >`+
item["Attrib_value"] +`</option>`
});
html += `</optgroup>`;
}
console.log('html',html);
$('#mySelect').html(html);
</script>
Since jQuery allows a nice api to create dom elements so I would use the following approach but other answer will work:
var data = {
"Color":[
{
"Id":"1",
"Attrib_name":"Color",
"Attrib_value":"Red"
},
{
"Id":"2",
"Attrib_name":"Color",
"Attrib_value":"Blue"
}
],
"Size":[
{
"Id":"3",
"Attrib_name":"Size",
"Attrib_value":"5.6"
},
{
"Id":"4",
"Attrib_name":"Size",
"Attrib_value":"5.1"
}
]
};
var select = $('<select/>');
$.each(data, function(g, colors) {
var group = $('<optgroup/>', {label:g});
$.each(colors, function(i, color) {
var option = $('<option/>', {
value: color.Attrib_value,
text: color.Attrib_value
});
select.append(group.append(option));
});
});
$('#dropdown').append(select);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='dropdown'></div>

I want to get my value from json data

i have json like this
{
"id":"1",
"name":"Kitchen Set",
"parent_id":"0",
},
{
"id":"2",
"name":"Bedroom",
"parent_id":"0"
},
{
"id":"3",
"name":"Living Room",
"parent_id":"0"
},
{
"id":"4",
"name":"Kitchen Set",
"parent_id":"1",
"price":"1000"
},
{
"id":"5",
"name":"Meja Bar",
"parent_id":"1",
"price":"2000"
},
and i want to add price: to my javascript
here is my question i want to get the price from my json to my javascript how can i do that??
i try this but it doesnt work
load_json_data('Price');
function load_json_data(price)
{
var html_code = '';
$.getJSON('int_fur_fin.json', function(data)
}
and this is my javascript
<script>
$(document).ready(function(){
load_json_data('Interior');
function load_json_data(id, parent_id)
{
var html_code = '';
$.getJSON('int_fur_fin.json', function(data){
html_code += '<option value="">Select '+id+'</option>';
$.each(data, function(key, value){
if(id == 'Interior')
{
if(value.parent_id == '0')
{
html_code += '<option value="'+value.id+'">'+value.name+'</option>';
}
}
else
{
if(value.parent_id == parent_id)
{
html_code += '<option value="'+value.id+'">'+value.name+'</option>';
}
}
});
$('#'+id).html(html_code);
});
}
$(document).on('change', '#Interior', function(){
var Interior_id = $(this).val();
if(Interior_id != '')
{
load_json_data('Furniture', Interior_id);
}
else
{
$('#Furniture').html('<option value="">Select Furniture</option>');
}
});
});
</script>
i use this javascript code to populate my dropdown
<form>
<select name="Interior Details" id="Interior" class="form-control input-lg">
<option value="">Select Interior Details</option>
</select>
<br />
<select name="Furniture" id="Furniture" class="form-control input-lg" required >
<option value="">Select Furniture</option>
</select>
</form>
You can use array.find() method to find the matching element. Also i have modified your JSON as a array.
items.find(t=>t.parent_id ==='1');
DEMO
var items = [{
"id":"1",
"name":"Kitchen Set",
"parent_id":"0",
},
{
"id":"2",
"name":"Bedroom",
"parent_id":"0"
},
{
"id":"3",
"name":"Living Room",
"parent_id":"0"
},
{
"id":"4",
"name":"Kitchen Set",
"parent_id":"1",
"price":"1000"
},
{
"id":"5",
"name":"Meja Bar",
"parent_id":"1",
"price":"2000"
}];
var result = items.find(t=>t.parent_id ==='1');
console.log(result);
EDIT
If you want multiple elements with matching id use array.filter.
var items = [{
"id":"1",
"name":"Kitchen Set",
"parent_id":"0",
},
{
"id":"2",
"name":"Bedroom",
"parent_id":"0"
},
{
"id":"3",
"name":"Living Room",
"parent_id":"0"
},
{
"id":"4",
"name":"Kitchen Set",
"parent_id":"1",
"price":"1000"
},
{
"id":"5",
"name":"Meja Bar",
"parent_id":"1",
"price":"2000"
}];
var result = items.filter(t=>t.parent_id ==='1');
console.log(result);

Select2.js: why is id the same as text on change for removed?

JSfiddle: http://jsfiddle.net/cjVSj/
I have a simple select2 with the range of possible tags set by the tags option and the preloaded tags set by values in the input field in the html.
When the on change event fires on the select2, the removed item seems to lose its id, reporting instead its text value.
To see the problem, adding a tag (e.g. west) correctly reports the added.id, but removing the existing east tags reports id = east, not 1356.
Any insight into how to gain access to the id of a tag upon removal?
HTML:
<script>
var tags = [{ "id": 1354, "text": "north", "restricted": false
}, {"id": 1355, "text": "south", "restricted": false
}, {"id": 1356, "text": "east", "restricted": false
}, {"id": 1357, "text": "west", "restricted": false
}];
</script>tags:
<input type="text" id="mytags" value="east" />
JS:
$(document).ready(function () {
$('#mytags').select2({
placeholder: 'Search',
allowClear: true,
minimumInputLength: 2,
multiple: true,
tags: tags,
tokenSeparators: [','],
});
$('#mytags').on("change", function (e) {
console.log("change " + JSON.stringify({
val: e.val,
added: e.added,
removed: e.removed
}));
if (e.added) {
alert('added: ' + e.added.text + ' id ' + e.added.id)
} else if (e.removed) {
alert('removed: ' + e.removed.text + ' id ' + e.removed.id)
}
});
});
There was an issue with your select2 declaration and syntax.
Further more, if you entered any other text, say "eas" or "test", your piece of code reflected that as it is. Check this scenario.
Updated fiddle: http://jsfiddle.net/ZBf5H/
To be specific, you did not give appropriate mapping to your tags. Please find how to access remote data in select 2 from here
The change of code is as below:
$(document).ready(function() {
var data=[{id:1354,text:'north',restricted:false},
{id:1356,text:'east',restricted:false},
{id:1357,text:'west',restricted:false},
{id:1355,text:'south',restricted:false}];
function format(item)
{ return item.text; }
$('#mytags').select2({
placeholder: 'Search',
allowClear: true,
minimumInputLength: 2,
multiple: true,
tags: tags,
tokenSeparators: [','],
data:{ results: data, text: 'text' },
formatSelection: format,
formatResult: format
});
Let me know if this works for you.
Ok... I've got a working solution, but I still don't exactly understand the difference between select2's tags and data options....
JSfiddle: http://jsfiddle.net/7e8Pa/
I'm initializing select2 with a list of all possible tags via the data option from an array, then selecting those for preloading: the initSelection function checks for ids in the and looks them up in the data array (the pre-stored one, not Select2's). Last, new tags may be added (the createSearchChoice does this). To hook this to my server, I'm just going to insert ajax calls where noted below in the on-change event handler (which gets called after createSearchChoice, and can overwrite the field values for the new object set in createSearchChoice).
JS:
function findWithAttr(array, attr, value) {
for (var i = 0; i < array.length; i += 1) {
if (array[i][attr] == value) {
return array[i];
}
}
}
$(document).ready(function () {
function format(item) {
return item.text;
}
$('#mytags').select2({
placeholder: 'Search',
minimumInputLength: 2,
multiple: true,
//tags: tags,
tokenSeparators: [','],
data: {
results: tags,
text: 'text'
},
initSelection: function (element, callback) {
var data = [];
$($('#mytags').val().split(",")).each(function (i) {
var o = findWithAttr(tags, 'id', this);
if (o) {
data.push({
id: o.id,
text: o.text
});
} else {
console.log("findWithAttr returned none; likely invalid id");
}
});
console.log("data = " + JSON.stringify(data));
callback(data);
},
createSearchChoice: function (term, data) {
console.log("create");
if ($(data).filter(function () {
return this.text.localeCompare(term) === 0;
}).length === 0) {
// call $.post() to add this term to the server, receive back id
// return {id:id, text:term}
// or detect this shiftiness and do it below in the on-change
return {
id: -1,
text: term
};
}
},
formatSelection: format,
formatResult: format
});
$('#mytags').on("change", function (e) {
console.log("change " + JSON.stringify({
val: e.val,
added: e.added,
removed: e.removed
}));
if (e.added) {
alert('added: ' + e.added.text + ' id ' + e.added.id);
//modifying the id here overrides what is assigned above in createSelection
e.added.id = 5;
} else if (e.removed) {
alert('removed: ' + e.removed.text + ' id ' + e.removed.id);
}
var selections = (JSON.stringify($('#mytags').select2('data')));
$('#selectedText').text(selections);
});
});
HTML:
<script>
var tags = [{
"id": 1354,
"text": "north",
"restricted": false
}, {
"id": 1355,
"text": "south",
"restricted": false
}, {
"id": 1356,
"text": "east",
"restricted": false
}, {
"id": 1357,
"text": "west",
"restricted": false
}];
</script>
<p>tags:
<input type="text" id="mytags" value="1355" style="width:80%" />
</p>
<p>Selected Options: <span id="selectedText"></span>
</p>
<p>Debug: <span id="debug"></span>
</p>

Categories