Im trying to populate a select (with the values from an array) depending on the option they select from the first dropdown
I have the arrays in my function, like so:
residential = ["R1_:_Single_Private_Dwelling","CH1_:_Self-Catering_Holiday_Unit","R2_:_Flats_or_Maisonettes_Up_to_3_floors_Purpose_Built","R3_:_Flats_or_Maisonettes_4_floors_and_over_Purpose_Built","CC7_:_Time_Share_Complex","R4_:_Houses_Converted_to_Flats_Up_to_2_Floors","R5_:_Houses_Converted_to_Flats_3_floors_and_over","MR_:_Hostel","R6_:_HMO","CC_:_Camping_Site","CC1_:_Caravan_Park","CC5_:_Chalet_Park","CC6_:_Caravan_And_Chalet_Park_","CC_:_Gypsy_Caravan_Site","XX1_:_Other"]; institutionalVal = ["MH2_:_Hospital","MH3_:_Hospital_(private)","MR1_:_(Care)_Home_for_older_people_(Over_65)","MR2_:_(Care)_home_for_adult_placements_"];
The user is selecting from a dropdown, with an ID of 'residential' for example and I want to populate a second select with the values from the array above.
So I'm grabbing the ID of the selected option, like so:
var org_cat = $(this).children(":selected").attr("id");
So, the value of org_cat for example would be 'residential', so I'm thinking i can just try and iterate through this as the array is called 'residential'
So I'm trying to loop through the array as below:
$.each(org_cat, function(value) {
$('#area_usage')
.append($("<option></option>")
.attr("value", value)
.text(value));
});
BUT, the variable 'org_cat' is not being seen as the array.
What am i doing wrong, do I have to tell JQuery that its an array somehow?
This is the error I'm getting.
TypeError: invalid 'in' operand a
What you are trying to do is referencing the variable "residential" (that is an array) by using a string. So for that you can have an object like:
var org_cat = $(this).children(":selected").attr("id"); // = "residential"
var obj =
{
"residential": ["R1_:_Single_Private_Dwelling","CH1_:_Self-Catering_Holiday_Unit","R2_:_Flats_or_Maisonettes_Up_to_3_floors_Purpose_Built","R3_:_Flats_or_Maisonettes_4_floors_and_over_Purpose_Built","CC7_:_Time_Share_Complex","R4_:_Houses_Converted_to_Flats_Up_to_2_Floors","R5_:_Houses_Converted_to_Flats_3_floors_and_over","MR_:_Hostel","R6_:_HMO","CC_:_Camping_Site","CC1_:_Caravan_Park","CC5_:_Chalet_Park","CC6_:_Caravan_And_Chalet_Park_","CC_:_Gypsy_Caravan_Site","XX1_:_Other"]; institutionalVal = ["MH2_:_Hospital","MH3_:_Hospital_(private)","MR1_:_(Care)_Home_for_older_people_(Over_65)","MR2_:_(Care)_home_for_adult_placements_"];
}
And get the array "residential" thought referencing the index in the object like:
obj[org_cat]
So on the jQuery each:
$.each(obj[org_cat], function(value) {
$('#area_usage')
.append($("<option></option>")
.attr("value", value)
.text(value));
});
Or if your variable "residential" is global, you can refer it through window object like window[org_cat] instead of obj[org_cat]
Related
Json Array Object
Through Ajax I will get dynamic data which is not constant or similar data based on query data will change. But I want to display charts so I used chartjs where I need to pass array data. So I tried below code but whenever data changes that code will break.
I cannot paste complete JSON file so after parsing it looks like this
[{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
You can use Object.keys and specify the position number to get that value
var valueOne =[];
var valueTwo = [];
jsonData.forEach(function(e){
valueOne.push(e[Object.keys(e)[1]]);
valueTwo.push(e[Object.keys(e)[2]]);
})
It seems like what you're trying to do is conditionally populate an array based the data you are receiving. One solution might be for you to use a variable who's value is based on whether the value or price property exist on the object. For example, in your forEach loop:
const valueOne = [];
jsonData.forEach((e) => {
const val = typeof e.value !== undefined ? e.value : e.average;
valueOne.push(val);
})
In your jsonData.forEach loop you can test existence of element by using something like:
if (e['volume']===undefined) {
valueone.push(e.price);
} else {
valueone.push(e.volume);
}
And similar for valuetwo...
You could create an object with the keys of your first array element, and values corresponding to the arrays you are after:
var data = [{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
var splitArrays = Object.keys(data[0]).reduce((o, e) => {
o[e] = data.map(el => el[e]);
return o;
}, {});
// show the whole object
console.log(splitArrays);
// show the individual arrays
console.log("brand");
console.log(splitArrays.brand);
console.log("volume");
console.log(splitArrays.volume);
// etc
I have a dropdown list that I need to dynamically populate based on the selection of another. It all works up to the point that I have to render the new data in the dropdown list after clearing the list first. The list clears, but then fails to populate the new data being returned from the controller. I am attempting to use .each for this.
Here's the controller method in question:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult UpdateDocumentSubType(string DocumentType)
{
List<SelectListItem> DocumentSubTypeList = new List<SelectListItem>();
PropertyModel model = new PropertyModel();
int DocTypeID = 0;
//get DocTypeID
DocTypeID = model.GetDocTypeID(DocumentType);
//gets new document subtype list
DocumentSubTypeList = model.GetDocumentSubTypes(DocTypeID);
//return document subtype list
return Json(DocumentSubTypeList, JsonRequestBehavior.AllowGet);
}
As you can see, I'm returning a serialized json result of List.
On the view, I have the following:
$.ajax({
url: '#Url.Action("UpdateDocumentSubType","Document")',
type: 'GET',
dataType: "json",
data: { DocumentType: SelectedDocTypeText },
async: true,
success: function (data) {
var select = $("#Docs_DocumentSubTypeID");
select.empty();
$.each(data, function (index, item) {
select.append($('<option></option>').val(item).html(index));
});
}
});
This is where it all falls apart. The code hits select.empty(): and executes it successfully, but then as the "text" value of the SelectListItem, it instead provides the index element of the array of objects. Essentially, the tags render something like this:
<option value="[object Object]">1</option>
<option value="[object Object]">2</option>
<option value="[object Object]">3</option>
<option value="[object Object]">4</option>
I have verified that the data IS being passed. When I take the .each and put it in its own function, call that function, and add "debugger;" to it, I can see the data in the resulting "data" as four elements of [object, object].
As you may have guessed, JQuery isn't my strong suit, so any assistance would be appreciated. :)
First you should not be returning List<SelectListItem> in your UpdateDocumentSubType method - there is no point returning the extra properties of SelectListItem back to the client when you never use them. All you need to return is an anonymous object containing 2 properties, one for the option value, and one for its display text.
You have not shown the model,but assuming it contains properties say int ID and string Name, then it would be (say)
var data = db.YourTable.Where(...).Select(x => new
{
Value = x.ID,
Text = x.Name
};
return Json(data, JsonRequestBehavior.AllowGet);
The reason why your seeing value="[object Object]" is that your returning an array of complex objects so item in $.each(data, function (index, item) { is referring to an object containing properties Value, Selected, Text, Group etc. (i.e. the properties of SelectListItem), so you script needs to be
$.each(data, function (index, item) {
select.append($('<option></option>').val(item.Value).html(item.Text));
});
I am new as well so this might not be correct.
Try
$('<option></option>').val(item[index]).html(index));
or
$('<option></option>').val(item[0]).html(index));
instead of what you wrote.
I need some more information. Can you share the github repo?
I am working on something very similar and this is what I did:
(Look at render function from line 85 to 96)
https://github.com/stephenhu3/codepal/blob/development/js/youtubeComponent.js
It worked for me.
I have a function writen in ajax that return a set of value:
$.each(data.dataa, function (i,item) {
$.each(item, function (index, dat) {
$str+=dat;
})
$ulSub.append( '<li id="'+item.id +'" class="ui-widget-content">' +$str+'</li>');
});
Each item has two attribute: the id and the lastname,
the value of each $str is a concatenation of the id and the lastname, but I want just the lastname not the id. I used the function item[2] but it's not working.
the result of my code is shwon as follow
What I want is just get the value of the lasname. I know that I should use item.lastname, but I want to ask if there are other methods to get the value of the lastname because the second attribute (lastname) is a variable.
Well, your case is quite simple, you always have an object with 2 properties: id and an unknown property. As objects do not have a defined order, you canĀ“t assume that the field you want is always in second position
One way is to iterate the keys, and pick the one that is not equal to id:
for(var key in item){
if(key != 'id'){
$str+= item[key]
}
}
A similar way is to pick the object keys, and filter out the id one, then access the object with that key:
$str+= item[Object.keys(item).filter(function(k){return k != 'id'})[0]]
If you know the possible values of the key, another way would be:
var possibleKeys = ['lastname', 'name', 'adress', 'phonenumber']
for(var key in item){
if(possibleKeys.indexOf(key) != -1){ // if its a valid key, append the value
$str+= item[key]
}
}
In your case, the first option is probably the best, but there are mutiple ways to do it
Here I created tag using web tutorials.
JSFIDDLE : http://jsfiddle.net/karimkhan/A5TJh/1/
Inside:
for (var i in tags){
tagString.push(tags[i].value);
}
if I alert(tags[i]) it alerts correctly.
But when I use tags before end of function that it alerts undefined.
My purpose is to store all tags in an array and push POST this array to PHP file. But the issue is I am not able to retrieve tags value in array. As it is already in tags array, I thought I could access it directly.
You need values like 1, 2, 3 or tags names like tag1, tag2, tag3?
Call someMethod with argument like tagString
instance.tagit({
tagSource: availableTags,
tagsChanged: function () {
//Get the tags
var tags = instance.tagit('tags');
var tagString = [];
//Pull out only value
for (var i in tags) {
tagString.push(tags[i].value);
}
someMethod(tagString);
//Put the tags into the input, joint by a ','
input.val(tagString.join(','));
function someMethod(tags) {
console.log(tags);
// call POST action
}
}
});
I think it's easier to just retrieve the values from the DOM, rather than try to store them in an array. If you store them in array as they are being created, then you have to keep an eye on changes, such as if the user deletes one of the tags.
So I would just retrieve the values when the user performs their submit action. The values are stored in a hidden unordered list and each has a class of .tagit-choice, so just iterate over the list and retrieve the text values:
DEMO
$('.tagit-choice').each(function () {
alert($(this).contents(':not(a)').text());
});
Naturally, you can use the each method to create an array once you're ready to post like this:
tagsForPost = [];
$('.tagit-choice').each(function (i) {
tagObj = {value: i, label: $(this).contents(':not(a)').text()};
tagsForPost.push(tagObj);
});
console.log(tagsForPost);
I'm trying to generate markers for every user in my $.each loop in such a way that I can select each marker using the corresponding userId of a given user.
$.each($.parseJSON(window.usersArray), function (i, user) {
window.userMarkers[user['id']] = L.marker(98.76, 12.34).addTo(map);
console.log(window.userMarkers[user['id']]);
});
EDIT
I get the error:
Cannot set property '3' of undefined, where 3 is the user's ID.
You need to create the object (or array depending on your needs) before you can add anything to it.
window.userMarkers = {};
$.each($.parseJSON(window.usersArray), function (i, user) {
window.userMarkers[user['id']] = L.marker(98.76, 12.34).addTo(map);
console.log(window.userMarkers[user['id']]);
});
Solution: Define the array before setting properties to it! Example:
window.userMarkers = new Array();