Data is returned as undefined - javascript

I have this sortable function in which I want to be able to add users to a group. When I drag the user from the user-table to the group-table, I want to able to check if that ID already exists in the group-table, and if it does I want to respond with a error-message. However, when I try to loop trou and get the ID's from the group-table, I'm getting a undefined value.
HTML-code:
<div class="userContainer">
<div id="userDiv">
<ul class="userList dragable" ></ul>
</div>
<div id="groupDiv">
<select id="DropDown"></select>
<input id="btnGetGroups" class="btn btn-success" type="button"
value="Hämta grupper" />
<select id="DropDownGroups"></select>
<input id="btnShowGroups" class="btn btn-success" type="button"
value="Visa grupp" />
<ul class="usersOfGroupList dragable"></ul>
</div>
</div>
Here is the code for filling the group-table with current users:
$('#btnShowGroups').click(function () {
var e = document.getElementById("DropDownGroups");
groupId = e.options[e.selectedIndex].value;
$('.usersOfGroupList').empty();
$.getJSON("mylinkgoeshere" + groupId + "", function (result) {
$.each(result, function (i, value) {
$('.usersOfGroupList').append($("<li id='userElement' data-userId='' ></li>").data('userId', value.Id).html(value.FirstName + " " + value.LastName));
$(".usersOfGroupList").addClass("addBorder");
});
});
});
As you can see I'm using 'userId' as key in the data-property here.
The sortable-code looks like this:
$(".dragable").sortable({
connectWith: ".usersOfGroupList",
remove: function (e, ui) {
var $this = $(this);
var childs = $this.find('li');
if (childs.length === 0) {
$this.text("Nothing");
}
},
receive: function (e, ui) {
var array = [];
var $this = $(this);
var children = $this.find('li');
for (var i = 0; i < children.length; i++) {
var specificId = children[i].item.data('userId');
array.push(specificId);
console.log(array);
};
In the receive-property, I'm trying to get the current userIDs by looping trough all the li-elements and then push the ID's into a array, but it will only return undefined. I've debugged and the li-elements are there, but it gives me this error-message:
Uncaught TypeError: Cannot read property 'data' of undefined
at HTMLUListElement.receive

Related

how to get and render selected values related data from array in jquery?

I have no expertise in javascript but I want to render this data which is showing in my console.log below
How can I make forloop or something like that to render this data in my html input?
create.html
<div class="col-sm-2">
<div class="form-group">
<label>Expected Values</label>
<input type="text" class="form-control" value="{{vital.expected_values}}" readonly>
</div>
</div>
<div class="col-sm-2">
<div class="form-group">
<label>Price</label>
<input type="text" class="form-control" value="{{vital.price}}" readonly>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#id_vitals").change(function () {
var vitals = $(this).val();
$.ajax({
url: $('#personForm').data('url'),
data: { 'vital_id': vitals },
success: function (response) {
console.log(response[vitals['name']])
}
});
});
})
</script>
I would do it somehow like that:
// Your data
let dataArray = [{data: 1, otherData: 2, elseData: 3}]
// The element, where you want to show it
let targetElement = document.getElementById('your-targer-id');
// The container element for elements
let newContainer = document.createElement('ul');
// Pure JS loop, easy to understand what is happening
// But you can also do it with .map();
for (let i = 0; i < dataArray.length; i++) {
// Add every line
newContainer.innerHTML+='<li>' + dataArray[i].data + '</li>';
// Or other things, depending how you want to show the data
newContainer.innerHTML+='<li> data value is: ' + dataArray[i].data + ' and otherData value is: ' + dataArray[i].otherData + '</li>'; //etc
}
// Append created list in target element
targetElement.appendChild(newContainer);
EDIT - now I see, that you want to display multiple values in text input, rather like so:
let dataArray = [...your-data-array]
let targetElement = document.getElementById('target-input');
for (let i = 0; i < dataArray.lenght; i++) {
// loop throug elements and add it to value attribute of input, separated by coma.
targetElement.value+=dataArray[i].expected_values + ', ';
}

Issues with using AJAX and JQuery to multiselect and capture information from JSON file

I have a live search function that parses information from a JSON file using AJAX and jQuery, and then is clickable. What I'm struggling to figure out is how to have the value (in this case, "happy" or "fat") populate a multiselect, and then once that's accomplished, capture the rest of the data in that JSON array to be utilized later.
$(document).ready(function(){
$.ajaxSetup({ cache: false });
$('#search').keyup(function(){
$('#result').html('');
$('#state').val('');
var searchField = $('#search').val();
var expression = new RegExp(searchField, "i");
$.getJSON('coretype.json', function(data) {
$.each(data, function(key, value){
if (value.identifier.search(expression) != -1)
{
$('#result').append('<li class="list-group-item link-class"> '+value.identifier+'</li>');
}
});
});
});
$('#result').on('click', 'li', function() {
var click_text = $(this).text().split('|');
$('#search').val($.trim(click_text[0]));
$("#result").html('');
});
});
I have gotten all the way to having the value be clickable, and have been unsuccessful figuring out the rest from there.
Here's the JSON file:
[
{
"identifier":"Happy",
"progressbar1": 3,
"progressbar2": 2,
"progressbar3": -2
},
{
"identifier":"Fat",
"progressbar1": -3,
"progressbar2": -2,
"progressbar3": 2
}
]
Ideally I'd like javascript to be able to capture the "progressbarX" values when someone types in the identifier, although I figure there's a much easier way to accomplish this...
<!-- Search -->
<br /><br />
<div class="container" style="width:900px;">
<h2 align="center">EnneaTest</h2>
<br /><br />
<div align="center">
<input type="text" name="search" id="search" placeholder="trait type" class="form-control" />
</div>
<ul class="list-group" id="result"></ul>
<br />
</div>
</div>
</div>
Here's the Plunker file
I created a kind of autocomplete drop down for search from json. And once one of the options from that dropdown is selected, I add that to the result list. At that time the whole object is pushed into searchObjects object. When the item from the list is clicked, that text is used to search the object associated with it. Hope this helps..
<!-- Search -->
<br /><br />
<div class="container" style="width:900px;">
<h2 align="center">EnneaTest</h2>
<br /><br />
<div align="center">
<input type="text" name="search" id="search" placeholder="trait type" class="form-control" />
</div>
<div id="searchResult"></div>
<div>
<ul class="list" id="result" style="color: red;"></ul>
</div>
<br />
</div>
<script>
$(document).ready(function(){
$.ajaxSetup({ cache: false });
$('#search').keyup(function(){
var searchField = $('#search').val();
var regex = new RegExp(searchField, "i");
var output = '<div class="row">';
$.getJSON('coretype.json', function(data) {
$.each(data, function(key, val){
if (val.identifier.search(regex) !== -1) {
console.log(val);
var thisVal = JSON.stringify(val);
output += "<h5 onclick='addToList("+thisVal+")'>" + val.identifier + "</h5>";
}
});
output += '</div>';
$('#searchResult').html(output);
});
});
$('#result').on('click', 'li', function() {
var click_text = $(this).text();
console.log(click_text);
var thisObj = [];
thisObj = findObject(click_text);
console.log(thisObj);
});
});
var searchObjs = [];
function addToList(obj) {
//console.log(obj);
$('#result').append('<li class="list-group-item link-class">'+obj.identifier+'</li>');
$('#searchResult').html('');
var item = {};
item ["identifier"] = obj.identifier;
item ["progressbar1"] = obj.progressbar1;
item ["progressbar2"] = obj.progressbar2;
item ["progressbar3"] = obj.progressbar3;
searchObjs.push(item);
console.log(searchObjs);
}
function findObject(identifier) {
var found = 0;
for (var i = 0, len = searchObjs.length; i < len; i++) {
if (searchObjs[i].identifier === identifier) {
return searchObjs[i]; // Return as soon as the object is found
found = 1;
}
}
if(found === 0) {
return null; // The object was not found
}
} ;
</script>

Angular 1.5 when select all in input checkbox, value won't bind to model

Hi I am using https://vitalets.github.io/checklist-model/ to bind data from a checkbox to the model. When a user selects a checkbox it successfully binds data. However, I need the options to also "select all" I have followed the instructions in the documentation and have tried mapping all the value in the array so when the user "selects all" all the values are binded into the model. Instead of that happening I get an array with value of null. Here is how the flow works
1)init() function is called returning data when the user loads the application
2)user selects an air_date
3)user gets syscode data return after ng-options getSyscodes() is called
4)A user can select multiple syscodes
5)User can "select all" this is where my issue is, when I call selectAll(), instead of returning every value in array, the array returns as "null" and I can't make a call to the API.
I would appreciate any suggestions thanks!
Here is my HTML
Array Structure of Every Object
{syscode:1233,readable_name: "MTV"}
<form>
<div class="form-group">
<pre>Selected Model: {{rc.selections.syscode}} </pre>
<label>Syscode</label>
<!-- <select class="form-control" ng-options="syscode.readable_name for syscode in rc.dropdowns.syscodes" ng-model="rc.selections.syscode" ng-disabled="rc.dropdowns.syscodes.length === 0">
</select> -->
</div>
<button type="button" class="btn btn-default btn-sm dropdown-toggle" data-toggle="dropdown" style="width:214px;height:33px;font-size:15px;margin-left:-16px;"><i class="fa fa-caret-down pull-right" aria-hidden="true" style="width:1em;"></i></button>
<ul class="dropdown-menu">
<button class="btn btn-success btn-md" ng-click="rc.selectAll()"><i class="fa fa-check" aria-hidden="true"></i>Select All</button>
<button class="btn btn-danger btn-md" ng-click="rc.unselectAll()"><i class="fa fa-times" aria-hidden="true"></i>Unselect All</button>
<li ng-repeat="value in rc.dropdowns.syscodes">
<input type="checkbox" checklist-model="rc.selections.syscode" checklist-value="value.syscode" ng-checked="rc.selections.checked" /> {{value.readable_name}}</li>
</ul>
</form>
And Controller
ReportsController.$inject = ['ReportService','$window', '$q'];
function ReportsController(ReportService, $window, $q){
//Sorting Values
var ctrl = this;
//Initial State Values
ctrl.results = [];
ctrl.pageDone = false;
ctrl.loading_results = false;
ctrl.search_enabled = false;
ctrl.searching = false;
//Initial data arrays
ctrl.dropdowns = {
air_dates:[],
syscodes:[],
syscodeArray:[]
};
ctrl.test = null;
//Data binding objects
ctrl.selections = {
air_date:null,
checked: null,
syscode:null,
getAll: false
};
//Get Syscodes
ctrl.selectSyscode = function(){
ctrl.search_enabled = true;
ctrl.dropdowns.syscodes = [];
ctrl.dropdowns.syscodeArray = [];
ReportService.getSyscodes(ctrl.selections).then(function(response){
ctrl.dropdowns.syscodes = response.data;
//This line below enables select all in UI
ctrl.dropdowns.syscodeArray.push(response.data);
console.log("SyscodeArray", ctrl.dropdowns.syscodeArray);
});
};
// Select All Logic
ctrl.selectAll = function(){
var newitems = [];
angular.forEach(ctrl.dropdowns.syscodes, function(syscode) {
ctrl.selections.checked = 1;
newitems.push(syscode.syscode);
});
ctrl.selections.syscode = newitems;
}
// Unselect All
ctrl.unselectAll = function(){
angular.forEach(ctrl.dropdowns.syscodeArray, function(user) {
ctrl.selections.checked = 0;
});
ctrl.selections.syscode = [];
}
//Search Logic by Syscode and Air_Date
ctrl.search = function () {
var defer = $q.defer();
if (ctrl.search_enabled) {
ctrl.searching = true;
ctrl.error = false;
ctrl.sort_by = {
col: 'market',
reverse: true
};
ctrl.filters = undefined;
ReportService.getAssets(ctrl.selections).then(function (response) {
ctrl.results = response.data;
console.log("It worked!!!",response.data);
ctrl.searched_once = true;
ctrl.searching = false;
defer.resolve('searched');
}, function (error) {
defer.reject('search-error');
ctrl.error = true;
ctrl.searching = false;
ctrl.error_data = error;
});
} else {
defer.resolve('no-search');
}
return defer.promise;
};
//Calls initial air dates
var init = function(){
ReportService.getAirDates().then(function(response){
ctrl.dropdowns.air_dates = response.data;
console.log(response.data);
ctrl.pageDone = true;
});
};
init();
}
angular.module('command-center-app').controller('ReportsController', ReportsController);
I tried this, I looped through the array and made a new array containing only "syscode". That array I assigned it ctrl.selections.syscode which is the model. This should be the correct answer
ctrl.selectAll = function(){
var newitems = [];
angular.forEach(ctrl.dropdowns.syscodes, function(syscode) {
ctrl.selections.checked = 1;
newitems.push(syscode.syscode);
});
ctrl.selections.syscode = newitems;
}
There is something wrong with your implementation i think. The library uses an array to handle the checked values in it. But i don't think you are doing that. Plus ng-checked should be there. So:
<li ng-repeat="value in rc.dropdowns.syscodes">
<input type="checkbox" checklist-model="rc.selections.checked" checklist-value="value.syscode" />
{{value.readable_name}}
</li>
In the controller:
// Select All Logic
ctrl.selectAll = function(){
ctrl.selections.checked = [];
angular.forEach(ctrl.dropdowns.syscodeArray, function(user) {
ctrl.selections.checked.push( //iterate over all syscodes and push here
});
}
// Unselect All
ctrl.unselectAll = function(){
ctrl.selections.checked = [];
}
Let me know how it goes.

get collection class names from common class name

I want the collection array with 'info', '321' and 'danger' in jquery/Javascript. I'm having following HTML code.
And I have to use '.etape' classname for this.
<input class="etape btn-info others">
<input class="etape btn-321 ">
<input class="etape btn-danger others1">
<input class="etape others">
My worst script:
<script>
$(document).ready(function() {
var myClass;
var classNames = $('.etape').attr('class').split(/\s+/);
$( ".cc" ).each( function(index, item) {
if(item.indexOf("btn-") == 0){
myClass[] = item;
}
});
});
</script>
Please help me.
Here's how to get ["info", "321", "danger"] from the posted markup
var classes = $('.etape').map(function() {
var m = this.className.match(/btn\-(.*?)(?:\s|$)/);
return m ? m.pop().split('-').pop() : m;
}).get().filter(Boolean);
FIDDLE
var collection = [];
var classRegex = /btn-.*\s/;
$(".etape").each(function(index,element) {
var className = $(element).attr('class').match(classRegex);
if(className != null){
var data = className[0].replace("btn-","").trim();
collection.push(data);
}
});
Use CSS attr selectors:
$('[class*="btn-"]').val('hello');
// returns: [<input class=​"etape btn-info others">​, <input class=​"etape btn-321">​, <input class=​"etape btn-danger others1">​]
demo: https://jsfiddle.net/tianes/dx91guLw/

Couldn't append span element to array object in Angularjs/Jquery

Am struggling hard to bind an array object with list of span values using watcher in Angularjs.
It is partially working, when i input span elements, an array automatically gets created for each span and when I remove any span element -> respective row from the existing array gets deleted and all the other rows gets realigned correctly(without disturbing the value and name).
The problem is when I remove a span element and reenter it using my input text, it is not getting added to my array. So, after removing one span element, and enter any new element - these new values are not getting appended to my array.
DemoCode fiddle link
What am I missing in my code?
How can I get reinserted spans to be appended to the existing array object without disturbing the values of leftover rows (name and values of array)?
Please note that values will get changed any time as per a chart.
This is the code am using:
<script>
function rdCtrl($scope) {
$scope.dataset_v1 = {};
$scope.dataset_wc = {};
$scope.$watch('dataset_wc', function (newVal) {
//alert('columns changed :: ' + JSON.stringify($scope.dataset_wc, null, 2));
$('#status').html(JSON.stringify($scope.dataset_wc));
}, true);
$(function () {
$('#tags input').on('focusout', function () {
var txt = this.value.replace(/[^a-zA-Z0-9\+\-\.\#]/g, ''); // allowed characters
if (txt) {
//alert(txt);
$(this).before('<span class="tag">' + txt.toLowerCase() + '</span>');
var div = $("#tags");
var spans = div.find("span");
spans.each(function (i, elem) { // loop over each spans
$scope.dataset_v1["d" + i] = { // add the key for each object results in "d0, d1..n"
id: i, // gives the id as "0,1,2.....n"
name: $(elem).text(), // push the text of the span in the loop
value: 3
}
});
$("#assign").click();
}
this.value = "";
}).on('keyup', function (e) {
// if: comma,enter (delimit more keyCodes with | pipe)
if (/(188|13)/.test(e.which)) $(this).focusout();
if ($('#tags span').length == 7) {
document.getElementById('inptags').style.display = 'none';
}
});
$('#tags').on('click', '.tag', function () {
var tagrm = this.innerHTML;
sk1 = $scope.dataset_wc;
removeparent(sk1);
filter($scope.dataset_v1, tagrm, 0);
$(this).remove();
document.getElementById('inptags').style.display = 'block';
$("#assign").click();
});
});
$scope.assign = function () {
$scope.dataset_wc = $scope.dataset_v1;
};
function filter(arr, m, i) {
if (i < arr.length) {
if (arr[i].name === m) {
arr.splice(i, 1);
arr.forEach(function (val, index) {
val.id = index
});
return arr
} else {
return filter(arr, m, i + 1)
}
} else {
return m + " not found in array"
}
}
function removeparent(d1)
{
dataset = d1;
d_sk = [];
Object.keys(dataset).forEach(function (key) {
// Get the value from the object
var value = dataset[key].value;
d_sk.push(dataset[key]);
});
$scope.dataset_v1 = d_sk;
}
}
</script>
Am giving another try, checking my luck on SO... I tried using another object to track the data while appending, but found difficult.
You should be using the scope as a way to bridge the full array and the tags. use ng-repeat to show the tags, and use the input model to push it into the main array that's showing the tags. I got it started for you here: http://jsfiddle.net/d5ah88mh/9/
function rdCtrl($scope){
$scope.dataset = [];
$scope.inputVal = "";
$scope.removeData = function(index){
$scope.dataset.splice(index, 1);
redoIndexes($scope.dataset);
}
$scope.addToData = function(){
$scope.dataset.push(
{"id": $scope.dataset.length+1,
"name": $scope.inputVal,
"value": 3}
);
$scope.inputVal = "";
redoIndexes($scope.dataset);
}
function redoIndexes(dataset){
for(i=0; i<dataset.length; i++){
$scope.dataset[i].id = i;
}
}
}
<div ng-app>
<div ng-controller="rdCtrl">
<div id="tags" style="border:none;width:370px;margin-left:300px;">
<span class="tag" style="padding:10px;background-color:#808080;margin-left:10px;margin-right:10px;" ng-repeat="data in dataset" id="4" ng-click="removeData($index)">{{data.name}}</span>
<div>
<input type="text" style="margin-left:-5px;" id="inptags" value="" placeholder="Add ur 5 main categories (enter ,)" ng-model="inputVal" />
<button type="submit" ng-click="addToData()">Submit</button>
<img src="../../../static/app/img/accept.png" ng-click="assign()" id="assign" style="cursor:pointer;display:none" />
</div>
</div>
<div id="status" style="margin-top:100px;"></div>
</div>
</div>

Categories

Resources