I work with a JavaScript app and populate the drop-down menu with a JSON list.
$("#address").append($('<option></option>').attr("value", "1").text(""));
$.each(wallets, function (index, wallet) {
if (selectedCurrency === wallet["currency"].toString().trim()) {
$("#address").append($('<option></option>').attr("value", "1").text(wallet["address"]));
}
})
The UI looks like this,
If I select the empty item (like in the picture), I would like to print empty in the console. Otherwise, I want to print the address value. My intention is to write more code, but, this is where I would like to get started. The code I have,
$("#address").change(function () {
if($(this).val()===""){
console.log('empty');
}
else{
console.log($(this).val());
}
}
However, it only prints 1 in the console and can't distinguish between the empty bar and the address in concern. If I use console.log("The value is " + $(this).text()); inside the change function, it prints every info all together in the console,
The value is mp51mPC38Wtcmybdyd9MPEB2bKnw6eYbCsmqXjM7Mmg6B5LWMad7mHJi339ddaj7xXdBmvXxP1GmXXKojWQJKjgeoASnXVNXCS47z6n41jE2BKKpV6LsPb7dDdStjtuJf1FrYvMMmw1jtrWU5DADxvNR421MKFW1fposgzVMBymnzcZVF4jtZtGAggM5GuLog3Y5o52Mx4xMmq5Rgggfgy2TiRsvtcGm3rxx12R8XbYi9omkdt7ouyJnDXUp4LzdRSRP3ZhU57gUDKy6n2F2QEKk6Fqqk2yMTope5MYp1RtpT949kemrkdfp6qoVN3YiyJhq6nXPvgr3f7YpkS9j
The JSON data I have is something like,
[
{
"id": 1,
"code": "BTC",
"address": "mp51mPC38Wtcmybdyd9MPEB2bKnw6eYbCs",
"currency": "Bitcoin"
},
{
"id": 2,
"code": "BTC",
"address": "mqXjM7Mmg6B5LWMad7mHJi339ddaj7xXdB",
"currency": "Bitcoin"
},
{
"id": 4,
"code": "BTC",
"address": "mvXxP1GmXXKojWQJKjgeoASnXVNXCS47z6",
"currency": "Bitcoin"
}
// some more data
]
What the issue here? My guess is I do something wrong to append the data to the drop-down list and needs to be changed.
I can provide more info if required ....
Just change the value 1 to "" in first option.
$("#address").append($('<option></option>').attr("value", "").text(""));
$.each(wallets, function (index, wallet) {
if (selectedCurrency === wallet["currency"].toString().trim()) {
$("#address").append($('<option></option>').attr("value", "1").text(wallet["address"]));
}
});
check this example.
$("#address").append($('<option></option>').attr("value", "").text(""));
$("#address").append($('<option></option>').attr("value", "1").text("123"));
$("#address").append($('<option></option>').attr("value", "2").text("456"));
$("#address").change(function () {
if($(this).val()===""){
console.log('empty');
}
else{
console.log($(this).val());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="address">
</select>
Related
I have a json data which looks like this:
[{
"id": 9,
"category": "Baby",
"items": "[{\"value\":\"Baby Foods\"}]",
"created_at": "2022-01-08T14:28:48.000000Z",
"updated_at": "2022-01-08T14:28:48.000000Z",
"deleted_at": null
},
{
"id": 10,
"category": "Adult",
"items": "[{\"value\":\"Adult Clothes\"},{\"value\":\"Adult Bags\"},{\"value\":\"Adult Shoes\"}]",
"created_at": "2022-01-09T10:46:34.000000Z",
"updated_at": "2022-01-09T10:46:34.000000Z",
"deleted_at": null
}]
It has a list of categories with its items. Now what I am trying to do now is to populate that data on select boxes in a way that if a user change category queried from JSON will show items (as shown on JSON) to another select box as options belonging to that category selected.
Here is what I have tried so far using jquery:
let dropdown = $('#category');
dropdown.empty();
dropdown.append('<option selected="true" disabled>Choose</option>');
dropdown.prop('selectedIndex', 0);
const url = 'http://localhost:8000/admin/categories/show';
// Populate dropdown with list of categories
$.getJSON(url, function (data) {
$.each(data, function (key, entry) {
dropdown.append($('<option></option>').attr('value', entry.category).text(entry.category));
})
});
Here is the result which shows categories on category select box perfectly:
I don't have idea how to get items if certain category is selected on another select box (second one) any help will greatly appreciated.
You can define an eventHandler for your category change event, and whenver it changes, you can read related items from the source data, and put items in the target option, like this:
let data = [{
"category": "Baby",
"items": "[{\"value\":\"Baby Foods\"}]",
},
{
"category": "Adult",
"items": "[{\"value\":\"Adult Clothes\"},{\"value\":\"Adult Bags\"},{\"value\":\"Adult Shoes\"}]",
}
]
let categories = $('#category');
let items = $('#items')
function fillDropdown(target, {data, prop}) {
$.each(data, function(key, data) {
target.append($('<option></option>').attr('value', data[prop]).text(data[prop]));
})
}
fillDropdown(categories, {data, prop: 'category'})
categories.on('change', function(e) {
items.html('');
let value = $(this).val();
if (value) {
let dataItem = data.find(v => v.category == value);
const options = JSON.parse(dataItem.items);
fillDropdown(items, {data: options, prop: 'value'})
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="category">
<option></option>
</select>
<select id="items"></select>
I have a JSON file which contains data. I can print the data using ANgularJS. It will show in row with a checkbox and there is a Delete button. I want to delete the data from display and as well as from JSON file. Delete process would be like, Click on the checkbox which you want to Delete > Click on the Delete button. This is my plnkr link :-
http://plnkr.co/edit/A07XJk1RQNmhSnLFqLxH?p=preview
api.json is the JSON file.
This is the JSON file look like :-
{
"1": {
"venture": "XYZ Informatics",
"member": [
{
"name": "abcd",
"email": "abcd#gmail.com"
}
],
"message": "This is good day",
"isclicked": false
},
"2": {
"venture": "BBC Informatics",
"member": [
{
"name": "xyz",
"email": "xyz#gmail.com"
}
],
"message": "This is bad day",
"isclicked": true
}
}
Add ng-model to checkbox....then iterate data and use delete if it is checked
$scope.delete = function() {
angular.forEach($scope.datas, function(val, key) {
if (val.isclicked) {
delete $scope.datas[key];
}
})
}
View
<form ng-repeat="data in datas">
<input type="checkbox" ng-model="data.isclicked">{{ data.venture }}
</form>
<button ng-click="delete()">Delete</button>
DEMO
Assuming you have your data is on the scope, you'd use the JavaScript delete function to remove an item from the array.
So...
delete $scope.data["1"]
Angular's digest should update anything watching that scope property automatically.
I have json that looks like this:
[
{
"Id": 1,
"Name": "Item1",
"Order": 1,
"Categories": [
{
"Id": 1,
"Name": "Item1-Subitem1",
"Order": 1,
"Subcategories": [
{
"Id": 1,
"Name": "Item1-Subitem1-Subsubitem1",
"Order": 2
},
{
"Id": 2,
"Name": "Item1-Subitem1-Subsubitem2",
"Order": 1
},
...
and with angular I need to display on first page (or route) link on main items. For example:Item1Item2And when clicked on them links should be displayed with names from 'Categories'For example:Item1-Subitem1Item1-Subitem2And when clicked on these links there should be displayed links with name from 'Subcategories'For example:Item1-Subitem1-Subsubitem1Item1-Subitem1-Subsubitem2
Now my first links work but I don't know how to get that nested data from same json according to value from url. When I click on links in first view I go to page I need but without data. No errors is displayed. I belive I need to parse id from url but how to achieve that?
It can be checked here http://plnkr.co/edit/GTfLFQepFcXzXYcIHnP0I am using ui-router
In secondList.js, you've defined your scope with the wrong name. It should be:
scope: {
secondList: '='
},
After you fix that, you're also missing the final factory in service.js:
app.factory('singleList', ['$http', function ($http) {
return {
get: function () {
return $http.get('data.json').then(function (re) {
return re.data;
});
}
};
}])
FormatSelection in select2Option removing data.
I am receiving my data in
$scope.superclasses = superclassDataList.data;
where superclassDataList is coming from service in angular.
Data i received from service is :
{
"data": [{
"name": "new Test",
"id": 4506898162253824,
"attendanceAllowed": true,
"subclasses": [{
"title": "HIN",
"children": null,
"entityName": "MyClass",
"entityId": 5136918324969472
},
{
"title": "ENG 101 A",
"children": null,
"entityName": "MyClass",
"entityId": 5699868278390784
}]
}
],
"success": true,
"errorMessage": ""
}
Code where i am applying my ng-grid to show this data:
<div ng-show="superclasses[row.rowIndex].edit"><div id="subclasses" ng-model="superclasses[row.rowIndex].subclasses" ui-select2="select2Options" data-placeholder="Add Subclasses" style="width:100%" multiple></div></div>
<div class="ngCellText" ng-class="col.colIndex()" style="display:inline" ng-show="!superclasses[row.rowIndex].edit" ng-repeat="subclass in superclasses[row.rowIndex].subclasses">{{subclass.title}} ,</div>
(I added one extra field "edit" in superclasses so don't be confuse with that. If it's true first div(Editable mode) will be visible else second(View mode))
Code for select2 i write is:
$scope.subclassNameFormat="";
$scope.select2Options = {
allowClear : true,
multiple: true,
width : 550,
minimumInputLength: 3,
query: function (query){
SuperclassService.getSubclassesUnassigned({searchTerm: query.term.toUpperCase()}, function(response) {
$scope.classesList = response.data;
var data = {
results: []
};
$.each($scope.classesList, function(){
if(this.list === undefined || this.list.length === 0) {
data.results.push({id: this.id, text: this.title,isApplied: false});
}
});
query.callback(data);
}, function(error){
console.log("Superclass is not deleted.... Please try again");
});
},
formatSelection: function format(state) {
if((state.title === undefined || state.title === "") && (state.text !== undefined && state.text !== "")){
$scope.subclassNameFormat = state.text;
}else if((state.text === undefined || state.text === "") && (state.title !== undefined && state.title !== "") ){
$scope.subclassNameFormat = state.title;
}
}
};
here getSubclassesUnassigned() method retrieve data from server on the basis of 3 character i entered to search: (minimumInputLength: 3),
Question: The data in $scope.superclasses comes from server is complete(JSON Data written above). And for a moment complete data of subclasses visible(when edit is false) (in this case name of subclasses HIN, ENG 101 A). Once it entered in "formatSelection" part of "$scope.select2Options" one data from "subclasses" array will be remove and it reflect on the "subclasses" column in grid (the code i write above) and show only one name (either "HIN" or "ENG 101 A"). I don't know why it get entered in "formatSelection" part of "select2options" because till data time "edit" field was false. (See in div code ng-show="!superclasses[row.rowIndex].edit" ). I don't know how it reflect the data. and even delete the data completely(2nd object of subclasses array.).
Have a same problem when value of div is in editable mode(ng-show="superclasses[row.rowIndex].edit") it only show one value of subclasses array.
data after passing control from FormatSelection:
{
"data": [{
"name": "new Test",
"id": 4506898162253824,
"attendanceAllowed": true,
"subclasses": [{
"title": "HIN",
"children": null,
"entityName": "MyClass",
"entityId": 5136918324969472
}]
}],
"success": true,
"errorMessage": ""
}
I tried everything from reading complete doc. about query and formatSelection from select2 but didn't find or understand anything, and also search on stackoverflow but didn't find any relevant link or didn't understand from those already on site. I know it might be silly question for some professionals but i started working on angular just 2 days ago.
Ask me in more explanation is required. I will try to provide everything that i know.
Thanks in advance.
PS: Please ignore My grammatical mistakes.
Try this code before "query :" in select2Option
initSelection: function(element, callback) {},
It will initialize your data for select2 which you are receiving in $scope.superclasses. It is working fine for me.
Is it possible to supply a variable to select a particular element within a JSON array element in order to select it?
Assuming I have many users:
"users": [
{ "id":"000000", "uname": "admin", "password": "admin", "phash": "b109f3bbbc244eb82441917ed06d618b9008dd09b3befd1b5e07394c706a8bb980b1d7785e5976ec049b46df5f1326af5a2ea6d103fd07c95385ffab0cacbc86",
"profile": {
"fullname" : "Admin Admin",
"datejoined": "01-01-2014",
"reputation": "100",
"displaypic": "http://www.google.com/logo.png",
"cart": {
"Cid" : "1000000",
"item": [
{ "Iid": "00000001", "quantity": "10" }
]
}
}
},
Is it possible to select the above element by supplying just the username using jQuery?
I have tried:
Note: uname in the jQuery is a variable with "admin" assigned
$.getJSON('ssUsers.json', function (data) {
$(data.users[uname].profile.cart.item).each(function () {
++cartItems;
});
With little luck:
[Error] TypeError: 'undefined' is not an object (evaluating 'data.users[uname].profile')
Using grep:
thisUser = $.grep(data.users, function(e) { return e.uname==uname});
Try this:
$.getJSON('ssUsers.json', function (data) {
for(i=0; i<data.users.length ; i++){
$(data.users[i].uname.profile.cart.item).each(function () {
++cartItems;
}
});