Getting repeated values inside dropdown - javascript

I am having a dropdown which is fetching values from json but as my json file having some repeated values so I want them only once ..before it was working fine as I was able to filter the values but when I included some more code it started again taking repeated values ..please have alook..Thank you..
$(document).ready(function() {
Variable usednames is filtering the values..
$.ajax({
url: "data.json,
dataType: "json",
success: function(obj) {
var jsObject = obj;
var usedNames = [];
$('<option>', {
text: 'Select your Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#dropdown1');
$('<option>', {
text: 'Select your List Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#checkbox');
$.each(obj, function(key, value) {
if (usedNames.indexOf(value.name) == -1) {
$("#dropdown1").append("<option value=" + key + ">" + value.name + "</option>");
usedNames.push(value.name);
}
/* $('<option>', {
text: 'Select your Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#dropdown1');
*/
$.each(usedNames, function(index, value) {
$('<option>', {
text: value['name'],
value: index
}).appendTo('#dropdown1');
});
/* $('<option>', {
text: 'Select your List Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#listbox');
*/
$('#dropdown1').change(function() {
$('#checkbox').empty();
$('<option>', {
text: 'Select your List Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#checkbox');
var selection = $('#dropdown1 :selected').text();
$.each(jsObject, function(index, value) {
if (value['name'] === selection) {
$('<option>', {
text: value['attr001'],
value: 'attr001'
}).appendTo('#checkbox');
$('<option>', {
text: value['attr002'],
value: 'attr002'
}).appendTo('#checkbox');
$('<option>', {
text: value['attr003'],
value: 'attr003'
}).appendTo('#checkbox');
My HTML file
<form name="myform" id="myForm">
<select id="dropdown1"></select>
<!-- <select id="listbox"></select> -->
<input type="checkbox">
<br>

I think I see why. You have this code :
if (usedNames.indexOf(value.name) == -1) {
$("#dropdown1").append("<option value=" + key + ">" + value.name + "</option>");
usedNames.push(value.name);
}
Which works (or should work) just fine. But after that, you have this :
$.each(jsObject, function(index, value) {
$('<option>', {
text: value['name'],
value: index
}).appendTo('#dropdown1');
});
By having a look at your code, it seems that jsObject is equal to obj. So, in the first part, you're indeed checking for repeated values, that you put in the array named usedNames.
But shortly after, you're appending jsObject to #dropdown1, so you're never using the array usedNames, which should only have unique values.
You should use usedNames after creating it, and forget about obj or jsObject, unless it caries some more information.
EDIT : Note that, when creating usedNames, you're also appending to your dropdown. So you're appending what will be the content of usedNames, and then appending jsObject.

You could fill a list of unique values before assigning it to the dropdown.
function unique(arr) {
var u = {}, a = [];
for(var i = 0, l = arr.length; i < l; ++i){
if(!u.hasOwnProperty(arr[i])) {
a.push(arr[i]);
u[arr[i]] = 1;
}
}
return a;
}
Most elegant way to create a list of unique items in JavaScript

Related

populate HTML form elements from object by jQuery

My from elements are written in Object. I need to populate HTML form elements from that. Problem is that Object contains different input types, structure, custom rules etc. For example, there will be text input, image type input, select box, radio, checkbox etc. So, I don't understand looping over the object will be good idea (I started this, but couldn't complete by myself :( ). I could write the html tag element in html file too. But, I must take the value from that object. So, what's the best solution for it?
Sample Object:
var formObj = {
username: {
value: null,
type: 'text',
placeholder: 'Enter username'
},
password: {
value: null,
type: 'password',
placeholder: 'enter password'
},
country: {
value: null,
type: 'select',
defaultText: 'Choose here',
option: [
{
value: '1',
label: 'Australia'
},
{
value: '2',
label: 'USA'
},
{
value: '3',
label: 'UK'
}
]
},
gender: {
value: null,
type: 'select',
defaultText: null,
option: [
{
value: 'male',
label: 'Male'
},
{
value: 'female',
label: 'Female'
},
{
value: 'other',
label: 'Other'
}
]
}
}
jsfiddle demo
your jsfiddle demo revised
Added some comments to your demo. I'd also look into template strings. They'll make your life easier and code cleaner :) and the single responsibility principle for breaking your code into easier to manage/read pieces.
var html = ''; // <-- Initialize as empty string for `+=`
$.each(formObj, function(key, value) {
if (value.value === null) {
value.value = '';
}
// Add label
html += '<label for="' + key + '">' + key + '</label>';
// Add input
if (value.type === 'select') {
// Type is select
html += '<select class="form-control">' + generateOptionPlaceholder(value.defaultText) + generateOptionMarkup(value.option) + '</select>';
} else {
html += '<input name="' + key + '" type="' + value.type + '" value="' + value.value + '" placeholder="' + value.placeholder + '" class="form-control" />';
}
console.log(html);
});
You could use a strategy pattern for this sort of thing. For any variance, used a dictionary where the keys are based off of the variant, and the values are a function to call for that variant.
For example, if your object with form data had a structure like this:
var form = {
"field1": {
type: "text"
value: "foo",
attrs: {...}
},
...
}
You can use a strategy to handle different field types. Your strategy dictionary might start our like this:
var FIELD_STRATEGY = {
"input": function (name, value, attrs) {
// General purpose method for <input>
// Needs type included in attrs
"text": function (name, value, attrs) {
// Constructs an <input type="text">
attrs.type = "text";
return FIELD_STRATEGY.input(name, value, attrs);
},
"option": function (value, label, attrs) {
// Constructs an <option>
},
"select": function (name, options, attrs {
// Constructs a <select>
var opts = options.map(function(opt) {
return FIELD_STRATEGY.option(
null,
opt.value,
opt.label);
}).join("");
var attr_str = Object.keys(attrs).map(function(attr) {
var value = attrs[attr];
return name + '="' + value '"';
}).join(" ");
return '<select name="' + name + '" ' + attr_str + '>' +
opts + '</select>';
}
};
To use it, loop over the field names and invoke strategies based on type:
var fields = Object.keys(form).map(function (name) {
var conf = form[name] || {};
var strategy = FIELD_STRATEGY[conf.type];
var rendered = "";
if (strategy) {
rendered = strategy(name, conf.value, conf.attrs);
}
return rendered;
});
This will give you a final fields list containing rendered strings based on the strategy for each field type.

Custom number of buttons tinymce

How can I create custom buttons tinymce buttons using JQuery? I would need n "Menu item" buttons. "n" would be defined depending on the selected data before opening the tinymce editor.
My buttons:
editor.addButton('addButtons', {
type: 'menubutton',
text: 'My button',
icon: false,
menu: [
{
text: 'Menu item 1',
onclick: function() {
editor.insertContent(' <strong>item1</strong> ');
}
}, {
text: 'Menu item 2',
onclick: function() {
editor.insertContent(' <strong>item2</strong> ');
}
}, {
text: 'Menu item 3',
onclick: function() {
editor.insertContent(' <strong>item3</strong> ');
}
}
]
});
I can get "n" value from a input type hidden using JQuery $("#totalButtons").val(). If totalButtons is 4, I would need 4 item buttons. Does it make sense? Is it possible to do?
Thanks
Updated Code:
var n = $('#total').val();
var menuItems = [];
tinymce.init({
selector: '#mytextareaTenant',
content_css: 'https://fonts.googleapis.com/css?family=Aguafina+Script|Alex+Brush|Bilbo|Condiment|Great+Vibes|Herr+Von+Muellerhoff|Kristi|Meddon|Monsieur+La+Doulaise|Norican|Nothing+You+Could+Do|Parisienne|Permanent+Marker|Sacramento|Yellowtail',
theme: 'modern',
menubar: false,
plugins: [
"print"
],
setup: function (editor) {
editor.on('init', function (e) {
renderEditorTenant();
for (var i=1; i<=n; i++){
var msg = ' <strong>#item' + i + '#</strong> ';
var obj = {
text: 'Menu item ' + i,
onclick: function() {
editor.insertContent(msg);
}
}
menuItems.push(obj);
}
});
Supposing you have a hidden input like this:
<input type="hidden" id="foo" name="zyx" value="3" />
You can get the value of the input and generate an array with n elements:
var n = $('#foo').val();
var menuItems = [];
for (var i=0; i<n; i++){
var msg = ' <strong>item' + i + '</strong> ';
var obj = {
text: 'Menu item ' + i,
onclick: function() {
editor.insertContent(msg);
}
}
menuItems.push(obj);
}
Now, just pass this array to the function you're using to generate the editor:
editor.addButton('addButtons', {
type: 'menubutton',
text: 'My button',
icon: false,
menu: menuItems
});

Create select DOM object with options in jQuery, Passing Attributes

How can I create a select DOM object with options in jquery similar to this input creation example?
$('<input />', {
name: 'age',
type: 'number',
placeholder: 'enter a number 1'
}).appendTo('#app');
Is there a way to create it passing attributes?
When creating an element with jQuery, any attribute, or even jQuery method, can be used in the options object, so you can do
$('<select />', {
name : 'test',
on : {
change : function() { /* stuff */ }
},
append : [
$('<option />', {value : "1", text : "Opt 1"}),
$('<option />', {value : "2", text : "Opt 2"}),
$('<option />', {value : "3", text : "Opt 3"})
]
}).appendTo('#app');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="app"></div>
You can create just by passing the entire select with option as string
$('<select name="number">' +
'<option>1</option>' +
'<option>2</option>' +
'<option>3</option>' +
'</select>').appendTo('body');
Another solution, using an array of objects having the required value and text and creating new select element based on the array information.
$(document).ready(function () {
var arrSelect = [
{ value: 1, text: 'One' },
{ value: 2, text: 'Two' },
{ value: 3, text: 'Three' }
];
var select = $('<select>').appendTo('body'); //Create new select element
//Loop through the array of objects and then create new option and append to select element
arrSelect.map(function (arr) { select.append($("<option>").attr('value', arr.value).text(arr.text)) });
$("body").append(select); //Append select to body element
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
1_ you can select Multiple DOM Multi DOM Select
like so :
$( "div, .sCLASS, p.myClass" ).whatever...
2_ you can also select Single DOM with concate Single DOM Select
like so :
$( "p" + ".sCLASS" ).whatever...
BUT you can't pass arg with it
The object select is created and then the options objects are appended.
$('<select />', {
id: 'my-numbers',
name: 'select-number'
})
.append($("<option/>", {
value: '1',
text: 'number1'
}))
.append($("<option/>", {
value: '2',
text: 'number2'
}))
.appendTo('#app');

Multiple Column returns undefined in MVC using MCAutocomplete Jquery UI

my multiple column in mvc returns undefined.
what do i missed? or there is wrong with my code? pls help.
Controller
public ActionResult EmployeeIDSearch(string term)
{
// Get Tags from database
using (var ctx = new DASH_FAEntities())
{
var tags = (from e in ctx.EmployeeMasters
where e.EMT_EmployeeID.ToLower().Contains(term.ToLower().Trim())
select new
{
EmployeeID = e.EMT_EmployeeID.Trim(),
FullName = e.EMT_FirstName.Trim() + " " + e.EMT_LastName.Trim(),
Department = e.EMT_Department.Trim()
}).ToArray();
return Json(tags, JsonRequestBehavior.AllowGet);
}
}
View
#Html.TextBox("EmployeeID", null, new { #class = "form-control", #placeholder = "Employee ID", #id="employeeid" })
Jquery
function customRenderItem(ul, item) {
var t = '<span class="mcacCol1">' + item[0] + '</span><span class="mcacCol2">' + item[1] + '</span><span class="mcacCol3">' + item[2] + '</span>',
result = $('<li class="ui-menu-item" role="menuitem"></li>')
.data('item.autocomplete', item)
.append('<a class="ui-corner-all" style="position:relative;" tabindex="-1">' + t + '</a>')
.appendTo(ul);
return result;
}
var columns = [{ name: 'Employee ID', minWidth: '100px' }, { name: 'Full Name', minWidth: '100px' }, { name: 'Department', minWidth: '100px' }]
$("#employeeid").mcautocomplete({
showHeader: true,
columns: columns,
source: '#Url.Action("EmployeeIDSearch", "Home")',
select: function (event, ui) {
this.value = (ui.item ? ui.item[0] : '');
return false;
}
});
mcautocomplete.js
I already checked the jsfiddle file of this plugin. I only just change the source and added another column. But still undefined when I look for the employee id.
I break point my controller where I get my source and it has a value every time I time for employee id.
Also I've already googled and i found nothing. It's been yesterday and I don't know what to do. I don't want to use other plugin because my web would be slow for using different plugin.
Please Help.
From the documentation, the syntax your using for the columns property is only suuitable if the source is an array of arrays. For example it would work it the data was
[['1', 'Joe Blogs', 'Administration'], ['2', 'John Doe', 'Finance']]
but your controller method is returning an array of objects, so you need to also specify the valueField property. Change the columns definition to
var columns = [{ name: 'Employee ID', minWidth: '100px', valueField: 'EmployeeID' },
{ name: 'Full Name', minWidth: '100px', valueField: 'FullName' },
{ name: 'Department', minWidth: '100px', valueField: 'Department' }]
where the value of valueField match the property name.
Edit
Since you now adding objects, not arrays, you also need to change
this.value = (ui.item ? ui.item[0] : '');
to
this.value = (ui.item ? ui.item.EmployeeID : '');
in order to display the selected value in the textbox (refer updated fiddle for a working example).

Hide column in jQuery MultiColumn Autocomplete

I have a fine working jquery multicolumn autocomplete. Now i have to add a column which should be hidden. Basically its a ID of the values. So when the user selects the value i could able to get the ID of the selected row.
//Code:
<script type="text/javascript">
var autocompleteSource;
var colValues = [];
var columns = [{ name: 'Workflow Name', width: '200px' }, { name: 'Workflow Category', width: '150px' }, { name: 'Status', width: '100px' }, { name: 'Workflow Owner', width: '150px' }];
$.ajax({
url: "/Home/LoadWorkflowDropdown",
datatype: 'json',
mtype: 'GET',
success: OnComplete,
error: OnFail
});
function OnComplete(result) {
autocompleteSource = $.parseJSON(result)
$.each(autocompleteSource, function () {
colValues.push([this.WorkflowName, this.WorkflowCategory, this.StatusName, this.UserName]);
});
$.widget('custom.mcautocomplete', $.ui.autocomplete, {
_renderMenu: function (ul, items) {
var self = this,
thead;
if (this.options.showHeader) {
table = $('<div class="ui-widget-header" style="width:100%"></div>');
$.each(this.options.columns, function (index, item) {
table.append('<span style="padding:0 4px;float:left;width:' + item.width + ';">' + item.name + '</span>');
});
table.append('<div style="clear: both;"></div>');
ul.append(table);
}
$.each(items, function (index, item) {
self._renderItem(ul, item);
});
},
_renderItem: function (ul, item) {
var t = '',
result = '';
$.each(this.options.columns, function (index, column) {
t += '<span style="padding:0 4px;float:left;width:' + column.width + ';">' + item[column.valueField ? column.valueField : index] + '</span>'
});
result = $('<li></li>').data('item.autocomplete', item).append('<a class="mcacAnchor">' + t + '<div style="clear: both;"></div></a>').appendTo(ul);
return result;
}
});
$("#search").mcautocomplete({
showHeader: true,
columns: columns,
source: colValues,
select: function (event, ui) {
this.value = (ui.item ? ui.item[0] : '');
return false;
}
});
}
</script>
Working Fiddle here
Here i have modified js code to add unique id to each record and to get that value when user selects a particular option from the auto-suggest list. Fiddle
HTML: Create a hidden field to store the id of selected option
<input type="hidden" name="selectedId" id="selectedId" />
JS: Added ids in the array and retrieved those ids in select function by index value.
var columns = [{
name: 'Color',
width: '100px'},
{
name: 'Hex',
width: '70px'}],
colors = [['Red', '#f00', '1'], ['Green', '#0f0', '2'], ['Blue', '#00f', '3']];
$("#search").mcautocomplete({
showHeader: true,
columns: columns,
source: colors,
select: function(event, ui) {
$('#selectedId').val(ui.item[2]);
this.value = (ui.item ? ui.item[0] : '');
return false;
}
});

Categories