Sunday, June 2, 2019

javascript - Take Distinct values to populate Drop down




   { "Result": { "tags": [ { "name": "ABC", "email": "abc1@example.com", "sms": 123 }, { 
"name": "ABC", "email": "abc2@example.com", "sms": 456 }, { "name": "ABC", "email":
"abc3@example.com", "sms": 789 }, { "name": "XYZ", "email": "xyz1@example.com", "sms": 976
}, { "name": "ABC", "email": "xyz2@example.com", "sms": 543 } ] } }


I have a JSON data like this. I want to Parse this JSON in PHP or Javascript to populate them in three drop downs.



Name | Email | SMS




But I need to Populate the distinct names in the dropdowns and populate email and sms based on selecting the name.



So far I just created the dropdowns.



Fiddle Link : http://jsfiddle.net/CAB2z/



Example:



Name should have : ABC | XYZ only once (Distinct : Should not repeat the same value).

When we select ABC, the three emails and phone numbers for "ABC" from the JSON should be populated in the second and third dropdown.


Answer



Try this,



$(function(){
var json = {
"Result": {
"tags": [{"name": "ABC","email": "abc1@example.com","sms": 123},
{"name": "ABC","email": "abc2@example.com","sms": 456},
{"name": "ABC","email":"abc3@example.com","sms": 789},

{"name": "XYZ","email": "xyz1@example.com","sms": 976},
{"name": "XYZ","email": "xyz2@example.com","sms": 543}]
}
};

var name = [],obj = {};
$(json.Result.tags).each(function (k, v) {
name[k] = (v.name);
obj[k] = {name: v.name,email: v.email,sms: v.sms};
});

$($.unique(name)).each(function (i, v) {
$('#name').append('');
});
$('#name').on('change', function () {
var $that = $(this);
$('#email').html('');$('#sms').html('');
$.each(obj,function (i, v) {
if( $that.val() == v.name) {
$('#email').append('');
$('#sms').append('');

}
});
}).change();
});


Live Demo


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...