Sunday 2 June 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...