Duplicate users(entries) should not be add in table - javascript

I'm facing an issue. i have a dropdown contains list of users fetching from database. When i select a user from dropdown it appends on below table and when i select the same user again it again appends on below table as a new row. So i want to stop duplicating same user in table.
Here's my View Code
<div class="form-group col-md-4 " style="display:none" id="user-container">
<label>User</label>
<select id="users" class="form-control" disabled="disabled">
<option value="">Select User</option>
</select>
<p class="validate-error"><span id="users_error"></span></p>
</div>
Here's my JavaScript Code
PostMyData(obj, '/Admin/Meetings/GetUserGroupUsers', (res) => {
if (res.Code === 0 || res.Code === -1) {
alert(res.Message);
}
if (res.Code === 1) {
$('#users').html('');
$('#users').append('<option value="">Select User</option>');
res.Data.map(item => {
$('#users').append(`<option value="${item.UserId}">${item.FirstName} ${item.LastName}</option>`);
});
$('#users').prop('disabled', false);
}

I think dynamically giving an id will do this job.Lets say you are giving giving id based of id value, then you can easily find if same id exits or not.
PostMyData(obj, '/Admin/Meetings/GetUserGroupUsers', (res) => {
users = document.getElementById("users");
if (res.Code === 0 || res.Code === -1) {
alert(res.Message);
}
if (res.Code === 1) {
users.html('');
users.append('<option value="">Select User</option>');
res.Data.map(item => {
if(!users.querySelector(item.UserId))
users.append(`<option value="${item.UserId}" id="${item.UserId}">${item.FirstName} ${item.LastName}</option>`);
});
users.prop('disabled', false);
}

I don't know what do you mean by duplicating same user in table, If you mean you want prevent duplicating user in the dropDown list you can try on this code, if not, please provide more details about the table you are working on.
...
const usersList= $('#users');
res.Data.forEach(item => {
if(usersList.find(`option[value=${item.UserId}]`).length > 0){
return ; // do nothing
}
usersList.append(`<option value="${item.UserId}">${item.FirstName} ${item.LastName}</option>`);
});
...

Related

event.target.value - how to get the key value?

There was a need to add a drop-down list with a choice of accounts. The chosen value is processed through "event.target.value". This handler takes the value visible to the user, but I only need the 'key' value of the selected record where the stored "account.Id". I've tried get access to key, but it doesn't seem to work.
First experience with JS, so apologize in advance if the question is incorrect or elementary.
Page:
<select class="slds-select" name = "accountSelect" onchange={changeHandler2} >
<template for:each={allAccounts.data} for:item="account">
<option key={account.Id} value={account.Id}>{account.Name}</option>
</template>
</select>
Handler:
changeHandler(event) {
if (field === 'accountSelect') {
this.accountId = event.target.options[event.target.selectedIndex].getAttribute('key');
}
}
Did you tried to use the data to get it :
changeHandler(event) {
if (field === 'accountSelect') {
this.accountId = allAccounts.data.find(item => item.Id === event.target.value);
}
}

Mean stack: display products into ng smart table

Im trying to display the product data using ng2-smart-table plugin.
I am able to get the products in the browser log, but i need to display the same onChange of a drop down value.
\app\components\layout\blank-page\blank-page.component.html
<form role="form">
<fieldset class="form-group">
<label>Select Category</label><br/><br/>
<select [(ngModel)]="selectedObject" (ngModelChange)="onChange(selectedObject)" name="selectedObject" class="form-control">
<option>--Select Category--</option>
<option *ngFor="let category of categories" [value]="category._id">{{category.category_name}}</option>
</select>
</fieldset>
</form>
//This is where table data is displaying, need to show my data here
<ng2-smart-table [settings]="view_update_items_settings" [source]="view_update_items_smart_data" (userRowSelect)="onUserRowSelect($event)" class="table table-hover table-striped"></ng2-smart-table>
app\components\layout\blank-page\blank-page.component.ts
onChange(categoryid) {
this.productService.getProductsOncategory(categoryid).subscribe(data => {
if (data.success) {
//this.selectedObject = data.mainProducts;
console.log(data)
console.log('Products obtained');
} else {
console.log('Not obtained!');
}
});
}
app\services\product.service.ts
getProductsOncategory(category_id){
console.log(category_id)
let catUrl="http://10.*.*.*:5000/products/getProductsOncategory"
let headers = new Headers();
headers.append('Content-Type','application/json');
let catIdObj = JSON.stringify({category_id:category_id})
console.log(catIdObj)
return this.http.post(catUrl,catIdObj,{headers:headers})
.map((response:Response)=>response.json())
.do(data=>console.log(JSON.stringify(data)))
.catch(this.handleError);
}
On selection of a value from drop down, i get data posted in my browser, i need to display the same in my ng2-smart-table
Bind "view_update_items_smart_data" with the data you obtain from server.
onChange(categoryid) {
this.productService.getProductsOncategory(categoryid).subscribe(data => {
if (data.success) {
//this.selectedObject = data.mainProducts;
console.log(data)
console.log('Products obtained');
this.view_update_items_smart_data.load(data);
} else {
console.log('Not obtained!');
}
});
}
For more information you can refer to
https://akveo.github.io/ng2-smart-table/#/examples/populate-from-server

How do I filter through list items based on multiple data attributes with jQuery?

Here is my HTML with all of my filters:
<div class="search-filters">
<div class="filter-block">
<label for="employee_type">Employee Type</label>
<select id="employee_type" class="category">
<option value="0">All</option>
<option value="designer">Designer</option>
<option value="manager">Manager</option>
<option value="developer">Developer</option>
<option value="quality-assurance">Quality Assurance</option>
</select>
</div>
<div class="filter-block">
<label for="years_xp">Years Experience</label>
<select id="years_xp" class="category">
<option value="0">Select years Experience</option>
<option value="1">1 year</option>
<option value="2">2 years</option>
<option value="3">3 years</option>
</select>
</div>
</div>
And my result list is below:
<ul class="result-set">
<li class="result" data-employee-type="designer" data-xp="3" >John Smith</li>
<li class="result" data-employee-type="manager" data-xp="2" >Billy Joe</li>
<li class="result" data-employee-type="developer" data-xp="5" >John Appleseed</li>
</ul>
So what I'm trying to do is filter the results with jQuery using the data attributes and select drop-downs on change. Right now only one or the other filter works with my jQuery code below. I tried using the .filter function in Jquery but it still only works when one drop-down is changed. If I change both it seems to be ignoring one condition.
My jQuery:
var category_filters = [];
$('.category').on('change', function() {
category_filters = [];
$('.search-filters select').each(function() {
if ($(this).val() != 0) {
var category = $(this).val();
category_filters[$(this).attr('id')] = category;
}
});
var employee_type = "";
var years_xp = "";
if ('employee_type' in category_filters) {
employee_type = category_filters['employee_type'];
}
if ('years_xp' in category_filters) {
years_xp = category_filters['years_xp'];
}
$(".result-set .result").hide().filter(function() {
if (employee_type != "") {
if ($(this).attr('data-employee-type') == employee_type) {
return true;
}
}
if (years_xp != "") {
if ($(this).attr('data-xp') == years_xp) {
return true;
}
}
}).show();
});
Any ideas on what i'm doing wrong? I've been stuck on this for almost 6 hours now and have looked at other examples but they just don't seem to work with my case.
Ok, so you want both filters to apply at the same time, not just show an item as soon as a single filter matches. In your filter function you are returning true as soon as you find a match, so that is where the problem lies.
I went ahead and updated your code a bit:
$('.category').on('change', function() {
var category_filters = [];
$('.search-filters select').each(function() {
if ($(this).val() != 0) {
category_filters[$(this).attr('id')] = $(this).val();
}
});
$(".result-set .result").hide().filter(function() {
var show = true;
for (var category in category_filters) {
show = show && $(this).data(category) == category_filters[category];
}
return show;
}).show();
});
And a demo: https://jsfiddle.net/04v4bqw5/1/
As you will notice I did some refactoring as well. This code assumes that the id of the filter matches exactly with the name of the data attribute you want to apply the filter to, so make sure to check the updated HTML as well.
The javascript has a lot less repetition, and you can add as much additional filters and matching data attributes as you want, and they will work without having to change the javascript.
As for the filter function, let me add some comments to explain
// assume we'll want to show the item
var show = true;
// go over each active filter
for (var category in category_filters) {
// check if the filter value matches the data attribute value, and any
// previous filters did not exclude this item yet (show &&)
show = show && $(this).data(category) == category_filters[category];
}
return show;
The reason you're getting this result is because of the behaviour of return true;. Think of this as a break statement - as soon as this is reached in the .filter function, it thinks its work there is done and it can stop processing. To overcome this, use some local booleans and then evaluate them both at the end of the function to decide whether to return true or not:
var etMatch = false, xpMatch = false;
if (employee_type != "") {
if ($(this).attr('data-employee-type') == employee_type) {
etMatch = true;
}
}
if (years_xp != "") {
if ($(this).attr('data-xp') == years_xp) {
xpMatch = true;
}
}
if (etMatch && xpMatch) { return true; }
You should use for each filter its function for comparison:
var compare = {
"employee-type": function(a,b) { return a===b},
"years-xp": function(a,b) { return (1*a)<=(1*b) }
}
$(".result-set .result").show().filter(function() {
var self = this;
return
!Object
.keys(category_filters)
.reduce( function(result, i) {
var filterValue = category_filters[i];
var itemValue = $(self).attr('data-'+i);
return result && compare[ i ]( filterValue, itemValue)
}, true)
}).hide();
[ https://jsfiddle.net/qqc9w4xm/ ]

Filtering section boxes won't remove blank spots

Fiddle
I am having trouble filtering my section box for a project I am working on. Ideally the first section box would collapse to display only the filtered options, but instead just leaves the filtered options blank.
My html is :
<select class="files">
<option class="{{file | types:type}}" ng-repeat="file in mdFiles" path="{{file.path}}" >{{file | types:type}}</option>
</select>
<select class="filters" ng-model="type" >
<option ng-model="type" ng-repeat="options in filters" value="{{options.filter}}">{{options.filter}}</option>
</select>
and my angular code:
app.filter('types', function () {
return function (input, type) {
console.log("i.t: " + input.type + ",t: " + type);
if(input.type == type || type == 'all')
return input.name;
}
});
I think you wanted something like this.
http://jsfiddle.net/nXH5J/
Your filter
app.filter('types', function () {
return function (files, type) {
var filtered = [];
angular.forEach(files, function(file) {
if(file.type == type || type == 'all') {
filtered.push(file);
}
});
return filtered;
}
});
And select
<select class="files">
<option ng-repeat="file in mdFiles | types:type" path="{{file.path}}">{{file.name}}</option>
</select>
You apply filtering on array and that filter is creating new array with filtered options.

How to remove an element on click

I need to remove the existing html when the selectbox val == 0. Here is my HTML,
<div class="info-cont">
<ul class="map-list">
<li>
<span class="left">
<label>Name 1</label>
</span>
<span class="right">
<select class="combo">
<option selected="selected" value="0"></option>
<option value="1">F name</option>
<option value="2">M name</option>
<option value="3">L name</option>
</select>
</span>
</li>
</ul>
</div>
Note : There are about 10 selectboxes in my page like the above,
and jquery for the above is,
$(document).ready(function () {
$('#save').click(function () {
var comboLength = $('.combo').length;
var selectedLength = $('.combo option:selected[value!=0]').length;
if (comboLength == selectedLength) {
alert('Thanks all the fields are selected');
return false;
}
if ($('.combo option:selected[value==0]')) {
$("div.info-cont ul.map-list li span.right").append("<br>Please select an appropriate value").addClass('validerror');
} else {
$("div.info-cont ul.map-list li span.right").html("");
$("div.info-cont ul.map-list li span.right").removeClass('validerror');
}
return false;
})
});
What i need to do in the else condition?(My else part is not funct). Also when i click the submit button for the second time, I should not append a html to which i already received in my first click. Any help? Thanks...
Change the if to
if($('.combo option:selected').val() === '0'){
All issues can be resolved with
$(document).ready(function(){
$('#save').click(function(){
var combo = $('.combo'), // get all combo elements
selected = $('.combo').filter(function(){
return $(this).find('option[value!="0"]:selected').length;
}), // get all valid combo elements
unselected = combo.not(selected); // get all non-valid combo elements
// clear previous error messages
combo
.closest('.right') // find containing .right element
.removeClass('validerror') // remove error class
.find('.errormessage') // find error message
.remove(); // remove error message
// chech if all combos are valid
if (combo.length === selected.length) {
alert('Thanks all the fields are selected');
return false;
}
// highlight non-valid elements
unselected
.closest('.right')
.addClass('validerror')
.append('<div class="errormessage">Please select an appropriate value</div>');
return false;
});
});
demo at http://jsfiddle.net/gaby/Y3RrH/

Categories