Using $(this) in JQuery .each - javascript

never asked question before as I can usually find the answer by hunting around here, but this has me stumped. I don't pretend to be any sort of JS/JQ expert, but I'm reasonably familiar with both. What I am trying to do is set a predefined CSS class to a group of text input elements within a form (The version of Django I am using unfortunately is not able to do this for me, and its not currently possible for me to upgrade as I don't have the time):
function setBsCss() {
var fields = $("input[type='text'], textarea").serializeArray();
jQuery.each(fields, function(i, field){
if ((this.name != "csrfmiddlewaretoken") && (this.name.indexOf("recaptcha") == -1)) {
$(this).addClass('someclass');
}
});
}
I'm not getting any errors, but the class is simply not being added to the elements. I could change the code and simply use a name or an ID selector, but I'd prefer to apply the class to the object itself if possible.
Any help greatly appreciated!

I can confirm the behaviour, but I don't understand it.
To solve this, you can avoid converting the jQuery object to an array and just use .each() instead of jQuery.each()
$("input[type='text'], textarea").each(function (i, field) {
if ((this.name != "csrfmiddlewaretoken") && (this.name.indexOf("recaptcha") == -1)) {
$(this).addClass('someclass');
}
});
See full JSFiddle
Update:
The problem lies in the .serializeArray()
.serializeArray()
Description: Encode a set of form elements as an array of names and values.
The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string.
serializeArray() does not create an array of DOM elements, but only an array of name/value pairs. So, this refers to an object
{
name: "other",
value: "somevalue"
}
which does not behave as expected, when used with addClass().

Related

loop in JSON with undefined elements

I am trying to figure out how to retrieve the values of a json of which i do not know the number of elements.
Example:
my json can be something like
var json = ["fixelement1":"value1","fixelement2":"value2","fixelement3":"value3","variableelement4":"value4","variableelement5":"value5"]
or
var json =["fixelement1":"value1","fixelement2":"value2","fixelement3":"value3","variableelement7":"value7","variableelement8":"value8", "variableelementN":"valueN"]
the only thing that I know is that the first 3 elements are always the same.
I use .indexOf() to search a value in fixelement3. What I would like to do is, if I find the element, I would like to retrieve the name of all the following elements (which number is variable and that are unknown) and their values.
javascript or jquery would work for me, but I have no idea..
thank you in advance!
var json ={
"fixelement1":"value1",
"fixelement2":"value2",
"fixelement3":"value3",
"variableelement7":"value7",
"variableelement8":"value8",
"variableelementN":"valueN"
}
for(prop in json){
console.log('key ======> value', prop, '=====>', json[prop]);
}

Safe way to check if array element exists?

I have a 2D array.
I currently access that array using notation such as:
myArray[5][9] (for example).
What is the safest way to check whether or not a certain array element exists?
For example, let's say I am looping through the array and retrieving a property of each array element like so:
myArray[5][9].firstName
I then come to myArray[9][11].firstName (for example) which doesn't exist. Clearly this will throw an exception as the element doesn't exist.
How can I deal with this? I'm not looping through the entire array (i'm accessing it's contents randomly and say using myArray.lengthin a for loop will not work.
Is there a JS function / method for checking whether or not an array element exists?
Thanks.
Safe call operator ?. looks fine. Warning: many, but not all implementations (and versions) of JavaScript supports it.
For your example it will looks like
myArray[5][9]?.firstName
EDIT: Thanks to Asaf's comment there is safer version
myArray?.[5]?.[9]?.firstName
like
if (!('firstname' in myArray[i][j])) { ... }
Just check it with if condition.
if(myArray[i][j].firstName){
}
You can use the hasOwnProperty method to check if an array item exists:
if (myArray.hasOwnProperty(x) && myArray[x].hasOwnProperty(y)) {
var name = myArray[x][y].firstName;
}
This checks both dimensions. If you know that the first index (x in the example) is always inside the range, you can skip the first test.
If you store some other values in the array also, you would need to check if the item has the firstName property:
if (myArray.hasOwnProperty(x) && myArray[x].hasOwnProperty(y) && myArray[x][y].hasOwnProperty('firstName')) {
var name = myArray[x][y].firstName;
}

How can I add elements to a part of a json by using jquery

I try to add elements in a particular way to the following JSON:
var data = [{"name":"google",
"ip":"10.10.10.01",
"markets":[{"name":"spain","county":"6002,6017,6018,6019,6020"},
{"name":"france","county":"6003,6005,6006,6007,6008,6025,6026,6027,6028,6029"},
{"name":"japan","county":"6004,6021,6022,6023,6024"},
{"name":"korea","county":"6000,6013,6014,6015,6016"},
{"name":"vietnam","county":"6001,6009,6010,6011,6012"}]},
{"name":"amazon",
"ip":"10.10.10.02",
"markets":[{"name":"usa","county":"10000,10001,10002,10003,10004,10005"}]},
{"name":"yahoo",
"ip":"10.10.10.03",
"markets":[{"name":"japan","county":"10000"}]}];
I want to add this element to the json:
newData = [{"name":"amazon",
"ip":"10.10.10.02",
"markets":[{"name":"mexico","county":"9000"}]}];
The result might be exactly this:
var data = [{"name":"google",
"ip":"10.10.10.01",
"markets":[{"name":"spain","county":"6002,6017,6018,6019,6020"},
{"name":"france","county":"6003,6005,6006,6007,6008,6025,6026,6027,6028,6029"},
{"name":"japan","county":"6004,6021,6022,6023,6024"},
{"name":"korea","county":"6000,6013,6014,6015,6016"},
{"name":"vietnam","county":"6001,6009,6010,6011,6012"}]},
{"name":"amazon",
"ip":"10.10.10.02",
"markets":[{"name":"usa","county":"10000,10001,10002,10003,10004,10005"},
{"name":"mexico","county":"9000"}]},
{"name":"yahoo",
"ip":"10.10.10.03",
"markets":[{"name":"japan","county":"10000"}]}];
I tried to use :
$.extend(data.markets, newData)
$.extend(true, data, newData); //this works only in the case every element is new.
but nothing works the way I pretend.
Could anyone give me a solution?
Thanks in advance.
You haven't created JSON, you've created a JavaScript literal object.
You could add this particular piece of newdata by
data[1].markets.push({"name":"mexico","county":"9000"})
Because you are dealing with javascript objects, you can write a function to check for the existence of data[n] and push data.
You have an array of objects, where each object is like the following:
var item = {"name":"...",
"ip":"...",
"markets":[ /*some objects here*/];
}
So why not just creating your custom method to insert elements? It could search in the array if an item with the same name and ip exists, and then:
If it does exist: append the markets to the existing item markets attribute (maybe you need to check again if they already exist). UPDATE:The code that #jasonscript added in his answer will do the job: once you have found where to add the market, just add it to the array. Again, maybe you'll have to check if that market was already in the array. Using jQuery it will be: $.extend(true, data[i],newData)
If it doesn't exist: just add the item to the array: $.extend(true, data,newData)
Stealing a little code from another answer:
$.each(data, function(item){
if(item.name == newData[0].name && item.ip == newData[0].ip) {
item.markets.push.apply(item.markets, newData[0].markets);
}
}
This assumes that you know that all the market items in the new object are different to the existing ones - otherwise you'd have to do a nested foreach or something. If you can change the notation of the objects a little you could think about using a dictionary-like object for Markets to make that a little cleaner.
In fact, changing data from an associative array would probably work for that too. Then you could easily check for existence with:
if(data[myNewDataName]){
//add to markets
} else {
data[myNewDataName] = myNewData;
}

Getting the default(?) element of a jQuery() selection

I am sure there is a simple solution.
The starting scenario was the following.
I create a <select> element and populate it dynamycally:
function CreateDropDown(name, id, optionList)
{
var combo = $("<select></select>").attr("id", id).attr("name", name);
$.each(optionList, function (i, item) {
combo.append("<option value='"+item.val+"'>" + item.el + "</option>");
});
return combo;
}
The aim was to extract the outerHTML. The following works right:
combo[0].outerHTML();
But I feel that indexing the array is very rough. At least in all that cases where the jQuery() function return a single element array.
Question
Whenever the jQuery() function return a single element array, is it possible to get the unique element without array indexing?
Demo
jQuery objects are inherently collections of DOM objects, and there is no syntactic way to treat a jQuery object as wrapper around a single item.
jQuery documentation suggests using get method to access individual DOM elements. It does not comment on performance difference between indexing operator and .get(), but it does say that "each jQuery object also masquerades as an array", so it would be ok to assume that indexing operator just adds another method call.
If you "feel that indexing the array is very rough", you could write your own nice helper method. Something like a:
window.$$ = function(){
return jQuery.apply(jQuery,arguments)[0];
}
Usage:
var combo = $$("<select></select>");
console.log( combo.outerHTML );
Use .get() to get the html elements.
http://api.jquery.com/get/

Delete index from array in javascript (using prototype framework, and within a class)

Im having trouble unsetting a key within an array using prototype (though this is probably a general javascript question) -- I have the following bit of code within my custom prototype class:
initialize: function(selector) {
this.selected = [];
this.selectcount = 0;
},
addSelected: function(value) {
this.selected.push(value);
this.selectcount++;
},
removeSelected: function(value) {
delete this.selected[value];
this.selectcount--;
},
adding to the array works fine, but I cant for the life of me figure out how to delete the specific ID within the array (value is referencing a particular id it is adding to the selected array, and I need to remove that same value from the array when removeSelected is clicked..) -- i also tried
this.selected.splice(value, 1);
But that didnt work either. Im basically looking or the equivelent of unset() in php.
Any help on what Im missing would be greatly appreciated.
Thanks in advance!
You are on the right track with splice(), but you need to pass it in the index of the value in the array, instead of the value itself.
indexOf() is the method to use for this:
var index = this.selected.indexOf(value);
if (index !== -1) {
this.selected.splice(index, 1);
this.selectcount--;
}
indexOf() returns -1 if the value does not exist in the array.
Note that Array.indexOf() is not supported on some older browsers, but you are safe to use it with Prototype.js, as it adds it for you.

Categories

Resources