Hi I am getting back a JSON encoded array ("html") from my Ajax call that I would like to add in the selectize as both value and text (I am using a tag) .
How can I do that ?
HTML
<input type="text" value="test" class="demo-default selectized" id="input-tags" tabindex="-1" style="display: block;">
JQUERY
try {
data = $.parseJSON(html);
var obj = jQuery.parseJSON(html);
outcome = (obj.outcome);
$('#input-tags').selectize({
delimiter: ',',
persist: false,
maxItems: 1,
create: function (input) {
return {
value: input,
text: input
}
}
});
}
You could map the array onto an array of objects, like this:
data = $.parseJSON(html);
var items = data.map(function(x) { return { item: x }; });
Then use "labelField" and "valueField" to specify the text/value:
$('#input-tags').selectize({
delimiter: ',',
persist: false,
options: items,
labelField: "item",
valueField: "item"
});
Fiddle Demo.
With ES6 you can reduce your oneliner a bit
const items = data.map(item => ({item}));
Related
I have a form , where I want some default selected value when the page loaded. Something like this:
Here is my current code which I am using for getting options from remote server:
(function () { // function for selectize
axios.get('/api/tags/', {
headers: {'Authorization': "JWT " + sessionStorage.getItem('token')}
}).then(function (response) {
let nisha = [];
response.data.map(function (hiren) {
let bunny = {'value': '', 'text': ''};
bunny['value'] = hiren.name;
bunny['text'] = hiren.name;
nisha.push(bunny);
});
let $select = $('#tags').selectize({
delimiter: ';',
persist: false,
options: nisha,
items: tags,
create: function(input) {
return {
value: input,
text: input
}
}
})
//var selectize = $select[0].selectize;
//selectize.setValue('something', true);
}).catch(function (error) {
console.error(error);
})
})();
You can pass default values in value attribute comma separated like below :
<input type="text" id="tags" class="demo-default selectized" value="awesome,neat" tabindex="-1" style="display: none;">
And if not working, try creating jsfiddle for this snippet.
Hope this will work.
I am trying to convert csv to array on angular 1.5+ionic on hebrew.
I am using ng-csv.
What I done till now:
Html:
<ng-csv-import
class="import"
content="csv.content"
header="csv.header"
header-visible="csv.headerVisible"
separator="csv.separator"
separator-visible="csv.separatorVisible"
result="csv.result"
encoding="csv.encoding"
encoding-visible="csv.encodingVisible"></ng-csv-import>
my controller is :
.controller('SettingsCtrl', function ($scope,$parse) {
$scope.csv = {
content: null,
header: true,
headerVisible: true,
separator: ',',
separatorVisible: true,
result: null,
encoding: 'Windows-1255',
encodingVisible: true
};
what else should be done to get the object as array.
Modify the code in your controller as
$scope.csv = {
content: null,
header: true,
headerVisible: true,
separator: ',',
separatorVisible: true,
result: null,
encoding: 'ISO-8859-1',
encodingVisible: true,
accept:".csv"
};
and your in your html
<ng-csv-import content="csv.content"
header="csv.header"
separator="csv.separator"
result="csv.result"
accept="csv.accept">
</ng-csv-import>
$scope.csv.result will now be an array of objects
$scope.csv.result will contain the result array from conversion. After the user selects a CSV file from the browse button, it will be populated. So, if you just wanted to do a data dump to the screen:
<div ng-if="csv.content">
{{csv.content}}
</div>
Chances are good you want to do more than that when it gets populated, so you can set up a watch on it
// (in controller)
$scope.$watch(
function() { return $scope.csv.content; },
function(newValue, oldValue) {
// do something on change
}
);
I'm using selectize.js like email contacts. But when I get mail list from database selectize shows undefined. When I type return value manuelly everything is fine. How can I populate it? Here is my code samples.
Return Value:
"[{"name":"Test User 1","id":"1"},{"name":"Test User 2","id":"2"}]"
C#
public JsonResult GetMails(){
var list = db.Members
.Where(x => x.IsActive == Status.Active)
.OrderBy(x => x.FullName)
.Select(c => new
{
name = c.FullName,
id = c.Id.ToString()
});
return Json(list, JsonRequestBehavior.AllowGet);
}
Javascript
<script type="text/javascript">
$(function () {
$.get("/mail/getmails", function (data) {
$("#MailReceivers").selectize({
persist: false,
plugins: ['remove_button'],
maxItems: null,
valueField: 'id',
labelField: 'name',
searchField: ['name', 'id'],
options: JSON.stringify(data),
create: function (input) {
return {name: input};
}
});
});
});
</script>
The answer is first parse json and than stringfy.
options: JSON.parse(JSON.stringify(data))
I want to autocomplete a drop down list.
This is my json string:
[{"ID":1,"Name":"david"},{"ID":2,"Name":"Paul"}]
This is my input:
<input type="text" id="tbNames" />
and this is my javascript:
//datas variable contains the json string
function BindNames(datas) {
$('#tbNames').autocomplete({
source: datas,
minLength: 0,
scroll: true,
select: function (event, ui) {
$("#tbNames").val(ui.item.Name);
return false;
}
}).focus(function () {
$(this).autocomplete("search", "");
});
}
The problem is that when I click on the 'tbNames' input the drop down list is displayed but names inside are not displayed BUT there are the names inside the list because when I click on on the drop down list one of the two name is displayed inside my input.
http://jsbin.com/wudidaqapo/1/edit?html,css,js,console,output
Thanks for your help.
Try this:
function BindNames() {
var datas=[{"ID":1,"Name":"david"},{"ID":2,"Name":"Paul"}];
$('#tbNames').autocomplete({
source: function (request, response) {
response($.grep(($.map(datas, function (v, i) {
return {
label: v.Name,
value: v.ID
};
})), function (item) {
return item.label;
}));
},
minLength: 0,
scroll: true,
}).focus(function () {
$(this).autocomplete("search", "");
});
}
Please see if it help for you.please use the 'label' property in your json object which the Autocompleter uses to find matches
[{"ID":1,"Name":"david","label":"david"},{"ID":2,"Name":"Paul","label":"Paul"}]
I'm trying to build out a json object in javascript/jquery that compares . Here's what I have
html:
<div class="field">
<div>size</div>
<div>large</div>
<div>medium</div>
<div>number</div>
</div>
js:
selectedObj = {
'fieldSize':false,
'sizeXSmall':false,
'sizeSmall':false,
'sizeMedium':false,
'sizeLarge':false,
'sizeXLarge':false,
'fieldName':false,
'fieldNum':false
};
if(jQuery('.field div:contains("size")')){selectedObj['fieldSize'] = true}
if(jQuery('.field div:contains("xs")')){selectedObj['sizeXSmall'] = true}
if(jQuery('.field div:contains("small")')){selectedObj['sizeSmall'] = true}
if(jQuery('.field div:contains("medium")')){selectedObj['sizeMedium'] = true}
if(jQuery('.field div:contains("large")')){selectedObj['sizeLarge'] = true}
if(jQuery('.field div:contains("xl")')){selectedObj['sizeXLarge'] = true}
if(jQuery('.field div:contains("name")')){selectedObj['fieldName'] = true}
if(jQuery('.field div:contains("number")')){selectedObj['fieldNum'] = true}
So ideally I would end up with an object that looks like this:
selectedObj = {
'fieldSize':true,
'sizeXSmall':false,
'sizeSmall':false,
'sizeMedium':true,
'sizeLarge':true,
'sizeXLarge':false,
'fieldName':false,
'fieldNum':true
};
I instead end up with an object where everything is true. Here is an example:
http://jsfiddle.net/vz600nd7/
Also, when I console log it before an after it looks like this:
It looks like the 'preview' is giving the right info but the actual view is not.
As I said in the comments, jQuery(selector) will return a jQuery object which will always be a truthy value. So your if condition will get executed every time.
I will try something like
var log = (function() {
var $log = $('#log');
return function(msg) {
$('<p/>', {
text: msg
}).appendTo($log)
}
})();
var map = {
'fieldSize': 'size',
'sizeXSmall': 'xs',
'sizeSmall': 'small',
'sizeMedium': 'medium',
'sizeLarge': 'large',
'sizeXLarge': 'xl',
'fieldName': 'name',
'fieldNum': 'number'
};
selectedObj = {
'fieldSize': false,
'sizeXSmall': false,
'sizeSmall': false,
'sizeMedium': false,
'sizeLarge': false,
'sizeXLarge': false,
'fieldName': false,
'fieldNum': false
};
var $els = jQuery('.field div');
$.each(map, function(key, value) {
selectedObj[key] = $els.is(':contains("' + value + '")')
});
log('After: ' + JSON.stringify(selectedObj))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="field">
<div>size</div>
<div>large</div>
<div>medium</div>
<div>number</div>
</div>
<div id="log"></div>
if you want to detect, if object exists, use:
if($('.field div:contains("size")')[0]) selectedObj['fieldSize'] = true;
...