How to search through Jquery Array - javascript

I'm trying to loop through an array using contains, but even if the value isnt it there it still appears true. The array is a list of checkboxes
function CheckBoxLogic(QId, Valuearray, UnCheckedValueArray) {
var CheckedChildArray = Valuearray;
var UnCheckedChildArray = UnCheckedValueArray;
$('.AnswerFunctions').each(function () {
//Get ParentID from child control
var ParentQuestionId = $(this).attr('ParentQuestionId');
//Get ParentValue from child control
var ParentQuestionValue = $(this).attr('ParentQuestionValue');
var QuestionId = $(this).attr('QuestionId');
if (ParentQuestionId === QId) {
if ($(CheckedChildArray + ":contains('" + ParentQuestionValue + "')")) {
$('#' + QuestionId + '-Question').removeClass('d-none');
}
//if ($(UnCheckedChildArray + ":contains('" + ParentQuestionValue + "')")) {
// $('#' + QuestionId + '-Question').addClass('d-none');
// };
}
});
}
}

That's not how you loop through an array. (At its simplest, what exactly do you expect [] + ":contains('" to be? You can't meaningfully concatenate a string and an array like that.)
If you want to check if an array contains a value, you can use the includes method. For example:
if (CheckedChildArray.includes(ParentQuestionValue)) {
$('#' + QuestionId + '-Question').removeClass('d-none');
}

Related

display second menu based on first one along with value and id

I am referring to another question display select options based on previous selections
I have while loop to fill the var data and inside a foreach loop to give the sub-menu and all work fine, var data = {'B|1':['B5|1','B4|2']
now after displaying menu1 How do I display second one, am just stopped there.
my code is:
for (var i in data) {
var ii = i.split('|');
$('#menu1').append('<option value=' + ii[1] + '>' + ii[0] + '</option>');
}
$('#menu1').change(function () {
var key = $(this).val();
$('#menu2').empty();
for (var i in data[key]) {
var ii = data[key][i].split('|');
$('#menu2').append('<option value=' + ii[1] + '>' + ii[0] + '</option>');
}
}).trigger('change');
menu1 is ok, now I need to show #menu2 with the value and text ??
This may help you
$('#menu1').change(function() {
var key = $(this).val();
var keyText = $('#menu1 :selected').text();
$('#menu2').empty();
for (var i in data[keyText +"|" + key]) {
var ii=data[keyText +"|" + key][i].split('|');
$('#menu2').append('<option value='+ii[1]+'>' + ii[0] + '</option>');
}
}).trigger('change');

How to setup if-statement with multiple conditions, which uses the valid condition's variable in the if-statement?

Okay, that title will sound a bit crazy. I have an object, which I build from a bunch of inputs (from the user). I set them according to their value received, but sometimes they are not set at all, which makes them null. What I really want to do, it make an item generator for WoW. The items can have multiple attributes, which all look the same to the user. Here is my example:
+3 Agility
+5 Stamina
+10 Dodge
In theory, that should just grab my object's property name and key value, then output it in the same fashion. However, how do I setup that if-statement?
Here is what my current if-statement MADNESS looks like:
if(property == "agility") {
text = "+" + text + " Agility";
}
if(property == "stamina") {
text = "+" + text + " Stamina";
}
if(property == "dodge") {
text = "+" + text + " Dodge";
}
You get that point right? In WoW there are A TON of attributes, so it would suck that I would have to create an if-statement for each, because there are simply too many. It's basically repeating itself, but still using the property name all the way. Here is what my JSFiddle looks like: http://jsfiddle.net/pm2328hx/ so you can play with it yourself. Thanks!
EDIT: Oh by the way, what I want to do is something like this:
if(property == "agility" || property == "stamina" || ....) {
text = "+" + text + " " + THE_ABOVE_VARIABLE_WHICH_IS_TRUE;
}
Which is hacky as well. I definitely don't want that.
if(['agility','stamina','dodge'].indexOf(property) !== -1){
text = "+" + text + " " + property;
}
If you need the first letter capitalized :
if(['agility','stamina','dodge'].indexOf(property) !== -1){
text = "+" + text + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
UPDATE per comment:
If you already have an array of all the attributes somewhere, use that instead
var myatts = [
'agility',
'stamina',
'dodge'
];
if(myatts.indexOf(property) !== -1){
text = "+" + text + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
UPDATE per next comment:
If you already have an object with the attributes as keys, you can use Object.keys(), but be sure to also employ hasOwnProperty
var item = {};
item.attribute = {
agility:100,
stamina:200,
dodge:300
};
var property = "agility";
var text = "";
if(Object.keys(item.attribute).indexOf(property) !== -1){
if(item.attribute.hasOwnProperty(property)){
text = "+" + text + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
}
Fiddle: http://jsfiddle.net/trex005/rk9j10bx/
UPDATE to answer intended question instead of asked question
How do I expand the following object into following string? Note: the attributes are dynamic.
Object:
var item = {};
item.attribute = {
agility:100,
stamina:200,
dodge:300
};
String:
+ 100 Agility + 200 Stamina + 300 Dodge
Answer:
var text = "";
for(var property in item.attribute){
if(item.attribute.hasOwnProperty(property)){
if(text.length > 0) text += " ";
text += "+ " + item.attribute[property] + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
}
It's unclear how you're getting these values an storing them internally - but assuming you store them in a hash table:
properties = { stamina: 10,
agility: 45,
...
}
Then you could display it something like this:
var text = '';
for (var key in properties) {
// use hasOwnProperty to filter out keys from the Object.prototype
if (h.hasOwnProperty(k)) {
text = text + ' ' h[k] + ' ' + k + '<br/>';
}
}
After chat, code came out as follows:
var item = {};
item.name = "Thunderfury";
item.rarity = "legendary";
item.itemLevel = 80;
item.equip = "Binds when picked up";
item.unique = "Unique";
item.itemType = "Sword";
item.speed = 1.90;
item.slot = "One-handed";
item.damage = "36 - 68";
item.dps = 27.59;
item.attributes = {
agility:100,
stamina:200,
dodge:300
};
item.durability = 130;
item.chanceOnHit = "Blasts your enemy with lightning, dealing 209 Nature damage and then jumping to additional nearby enemies. Each jump reduces that victim's Nature resistance by 17. Affects 5 targets. Your primary target is also consumed by a cyclone, slowing its attack speed by 20% for 12 sec.";
item.levelRequirement = 60;
function build() {
box = $('<div id="box">'); //builds in memory
for (var key in item) {
if (item.hasOwnProperty(key)) {
if (key === 'attributes') {
for (var k in item.attributes) {
if (item.attributes.hasOwnProperty(k)) {
box.append('<span class="' + k + '">+' + item.attributes[k] + ' ' + k + '</span>');
}
}
} else {
box.append('<span id="' + key + '" class="' + item[key] + '">' + item[key] + '</span>');
}
}
}
$("#box").replaceWith(box);
}
build();
http://jsfiddle.net/gp0qfwfr/5/

How can iterate over JSON object and print its properties and their values?

I want to navigate each property in the JSON below in JavaScript. The below JSON contains two records for reference but in real time will have numerous such records.
{"Record_0":[{"Status":"CREATED","CreatorLoginId":"sandhya","Name":"G1"}],"Record_1":[{"Status":"CREATED","CreatorLoginId":"San","Name":"G2"}]}
I want to get the values of the fields "Status", "CreatorLoginId" and "Name" to assign them to something else.
How should I do it?
var myJSON = JSON.parse('{"Record_0":[{"Status":"CREATED","CreatorLoginId":"sandhya","Name":"G1"}],"Record_1":[{"Status":"CREATED","CreatorLoginId":"San","Name":"G2"}]}');
for(var pr in myJSON)
{
console.log(myJSON[pr][0].Status);
console.log(myJSON[pr][0].CreatorLoginId);
console.log(myJSON[pr][0].Name);
}
Print how? If you mean output to the js console it would be
for (index in object) {
console.log(index + ': ' + object[index]);
}
If you mean add it to a web page, just replace console.log with a little markup:
var parent = document.getElementById('parentID');
for (index in object) {
parent.innerHTML += index + ': ' + object[index] + '<br>';
}
For nested objects (including arrays)
function print(object, parent) {
for (index in object) {
if (typeof object[index] == 'object') {
print(object[index});
}
parent.innerHTML += index + ': ' + object[index] + '<br>';
}
}
EDIT: don't forget to JSON.parse(): the string first before iterating
//Iterating through the groups
for (var currentRecord in groupInformation)
{
store.data.items.push({serial: {}, groupName: {}, createdBy: {}, status: {} });
store.data.items[iNoOfGroups].serial = iNoOfGroups + 1;
store.data.items[iNoOfGroups].groupName = groupInformation[currentRecord][0].Name;
store.data.items[iNoOfGroups].createdBy = groupInformation[currentRecord][0].CreatorLoginId;
store.data.items[iNoOfGroups].status = groupInformation[currentRecord][0].Status;
iNoOfGroups++;
}
var myJSON = JSON.parse('{"Record_0":[{"Status":"CREATED","CreatorLoginId":"sandhya","Name":"G1"}],"Record_1":[{"Status":"CREATED","CreatorLoginId":"San","Name":"G2"}]}');
for(var key in myJSON){
console.log(myJSON[key][0].Status);
console.log(myJSON[key][0].CreatorLoginId);
console.log(myJSON[key][0].Name);
}`

Add random class to an Appended div ? (jquery)

This is all of my code for the object I'm working with, but I'm thinking it's only the "create building in screen" part you really need to help me with.
My goal is to have it where instead of saying class="House houseRed", it says something like class="House +'randomClass'" etc, and that variable holds my other class names(i have 5 total).
It's for a mini-game I'm working on, and I need the buildings that spawn to have different looks, based on their class names.
//CREATE BUILDING IN MEMOMORY
function CreateHouseInMemory() {
//GET VALUES
var sAddress = $("#HouseAddress").val();
var sUniqueId = getUniqueId();
var iMaxResidents = $('input[name=housemaxresidents]').val();
var oHouse = {
sType: "House",
sAddress: sAddress,
sId: sUniqueId,
iMaxResidents: iMaxResidents,
Residents: aResidents = [],
babyInHouse: false
};
oCity.aBuildings.push(oHouse);
console.dir(oCity.aBuildings);
return oHouse;
}
//CREATE BUILDING IN SCREEN
function CreateHouseInScreen(oHouse)
{
$("#City").append('<div id="' + oHouse.sId + '" class="House houseRed" title="' + oHouse.sAddress + '"></div>');
$(".House").draggable();
$(".House").droppable();
}
;
//SPAWN BUILDING
$("#BtnCreateHouse").click(function() {
var oHouse = CreateHouseInMemory();
CreateHouseInScreen(oHouse);
});
Something like this
var classesnames = ['toto', 'titi', 'tata', 'tutu'],
classrandom = classesnames[Math.floor(Math.random() * classesnames.length)];
$("#City").append('<div id="' + oHouse.sId + '" class="House '+ classrandom +'" title="' + oHouse.sAddress + '"></div>');
Create an array of the target class names
var array = ['one', 'two','three','four', 'five'];
//then
var random = array[Math.floor(Math.random() * array.length)]
You can add a class randomly in a way like this:
function CreateHouseInScreen(oHouse)
{
var classes = ['houseRed', 'houseBlue', 'houseGreen'];
var randomIndex = Math.floor(Math.random() * classes.length);
var div = $('<div id="' + oHouse.sId + '" class="House" title="' + oHouse.sAddress + '"></div>');
div.addClass(classes[randomIndex]);
$("#City").append(div);
$(".House").draggable();
$(".House").droppable();
}
You could use something like
i = parseInt(Math.random() * 4)
to either generate an array index for an array of classes, e.g
classArray = ['class1', 'class2', 'class3', 'class4', 'class5']
obj.className = classArray[i]
or convert the integer to a string and append it to a constant string, e.g
obj.className = "myClass" + i.toString().

Loop through jquery data() object to get keys and values

I have a data() object containing some json.
Is there a way I can loop through the object and grab each parts key and value?
This is what I have so far:
function getFigures() {
var propertyValue = getUrlVars()["propertyValue"];
$.getJSON(serviceURL + 'calculator.php?value=' + propertyValue, function(data) {
figures = data.figures;
$.each(figures, function(index, figure) {
$('#figureList').append('<li> index = ' + data.figures.figure + '</li>');
});
});
$('#figureList').listview('refresh');
}
The json looks like this:
{"figures":{"value":"150000","completion":"10.00","coal":"32.40","local":"144.00","bacs":"35.00","landRegistry":"200.00","solFee":"395.00","vatOnSolFees":79,"stampDuty":1500,"total":2395.4}}
Apologies if its simple, I'm new to jQuery and couldn't find anything on SO that helped.
You can get the key and value like this
$.each(data.figures, function(key, val) {
console.log('Key: ' + key + ' Val: ' + val)
});​
So change your code to
$('#figureList').append('<li>'+ index + ' = ' + figure + '</li>');
Demo: http://jsfiddle.net/joycse06/ERAgu/
The parameters index and figure contains the parameter name and value. I think that you want to concatenate the parameters into the string:
$('#figureList').append('<li>' + index + ' = ' + figure + '</li>');
An alternative is to create the list item element and set the text of it, that would also work if the text contains any characters that need encoding:
$('#figureList').append($('<li/>').text(index + ' = ' + figure));
function getFigures() {
var propertyValue = getUrlVars()["propertyValue"];
$.getJSON(serviceURL + 'calculator.php?value=' + propertyValue, function(data) {
$.each(data['figures'], function(index, val) {
here grab "val" is key
$.each(data['figures'][index], function(col, valc) {
here grab "col" is value
}
}
}
bye

Categories