How to create array in jquery - javascript

I want to create the width array of each children of selected element. I tried :
var width = $(element).children().map(function () { return this.style.width; });
But this is not working. When i alert(width[0]) then instead of showing width it shows objectHtmlElement. What i am doing wrong ?

Try .width() the style property only works if you set inline styles.
var widths = $(element).children().map(function () { return $(this).width(); });

If you want to get the basic array, you should call get method, map method returns a jQuery-wrapped array.
As the return value is a jQuery-wrapped array, it's very common to get() the returned object to work with a basic array.
var widths = $(element).children().map(function() {
return this.style.width;
}).get();

var obj = $('li');
var arr = $.makeArray(obj);
Result would be:
(typeof obj === 'object' && obj.jquery) === true;
jQuery.isArray(arr) === true;

use jquery width() and get() after map:
var widths = $(element).children().map(function() {
return $(this).width();
}).get();

Related

How can I avoid "Cannot read property" error when the element isn't exist?

Here is my code:
category = $(document).find(".chosen-single:not(.chosen-default) > span:first-child")[0].outerHTML
Sometimes it throws:
Uncaught TypeError: Cannot read property 'outerHTML' of undefined
What kind of condition should I put on the way of that?
One nice trick is to use an anonymous function, like this, where you pass the query as a parameter
category = (function (el) {
return (el) ? el.outerHTML : '';
})($(document).find(".chosen-single:not(.chosen-default) > span:first-child")[0]);
It will save you setting up an extra variable and an if/then/else statement.
Make your code look something like this:
var element = $(document).find(".chosen-single:not(.chosen-default) > span:first-child")[0];
if(element) {
category = element.outerHTML
}
it's seems that sometimes the element you are searching is missing, so the result is undefined, to avoid this issue, check if found what you queried for
Either check the native DOM element or check the length of the jQuery object:
var obj = $(document).find(".chosen-single:not(.chosen-default) > span:first-child")[0];
var category = "";
if (obj) category = obj.outerHTML;
Checking the length:
var $obj = $(document).find(".chosen-single:not(.chosen-default) > span:first-child");
var category = "";
if ($obj.length) category = obj.outerHTML;
Just store the element in a variable, then check it before accessing:
var $chosenItem = $(document).find(".chosen-single:not(.chosen-default) > span:first-child")[0];
category = $chosenItem && $chosenItem.outerHTML;
Or substitute your conditional of choice.
Create a variable that counts the number of elements with that particular class, then create an if statement.
For example:
var chosenClass = document.querySelectorAll('.chosen-single').length;
if(chosenClass == 0) {
null;
}
else {
}

Combine find/filter function in jQuery while locating DOM elements

I want to find all elements inside #Grid, then inside a first "TR" tag they should have attribute role="row" and attribute role="columnheader".
I've got it and it works fine.
Example:
var elements = $("#Grid").find("tr").attr("role","row").first().find("th").attr("role", "columnheader");
What I want to do is to filter it only to elements which meet the condition: offsetWidth < scrollWidth
I tried like below, but this is the incorrect result:
var elements = $("#Grid").find("tr").attr("role", "row").first().find("th").attr("role", "columnheader");
var filtered = elements.filter(function () {
return $(this).offsetWidth < $(this).scrollWidth;
});
I can use this function as well, but I don't really know how to combine it in jQuery:
function isEllipsisActive(e) {
return (e.offsetWidth < e.scrollWidth);
}
Should work:
var filtered = elements.filter(function () {
return this.offsetWidth < this.scrollWidth;
});
Don't use $(this), use the element variable existing in the filter function.
var filtered = elements.toArray().filter(function (e) {
return e.offsetWidth < e.scrollWidth;
});

Get jQuery element by stored data

Using .data() function we can store data in jQuery objects:
From documentation:
Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.
Example:
// sets "string" value to "test"
$(".myClass").data("test", "string");
$(".myClass").data("test"); // returns "string"
This is simple.
Now I want to get all jQuery elements from page that have "string" value associated with "test".
Is this possible? Is there any function that would do this?
You can use .filter() to filter the elements
var $filtered = $('<target-elements>').filter(function(){
return $(this).data('test') == 'test'
})
Demo: Fiddle
I'm affraid .data() doesn't actually add a data- attribute to your html element.
A possible workaround would be to iterate over the elements:
$('.myClass').each(function(){
var el = $(this);
if(el.data("test") === "string") {
console.log("found !");
}
});
Here is a fiddle:
http://jsfiddle.net/5p9LX/1/
Try using jQuery.grep() to filter all elements
Get all elements with 'test' data key:
var arrElements = $.grep($("*"), function (a) { return $(a).data("test") != undefined; });
var $filteredElements = $(arrElements);
Get all elements with 'test' data value equals to 'string':
var arrElements = $.grep($("*"), function (a) { return $(a).data("test") == "string"; });
var $filteredElements = $(arrElements);

jQuery $.inArray() always return -1 with an array of object

I have an array of object, that contain key value pair of columnNames.
when i check if a particular columnName exists it alwayz returns -1
Here is an sample http://jsfiddle.net/trLkt/6/, Help will b appriciated
You're searching for string values in the columnModel array, but you're storing objects in it (columnModel.push({'colName': $(this).text()});). $.inArray() cannot decide by itself to compare against the colName property of each array element, it simply compares the value you're searching for against each array element.
Two things you can do:
Add strings to the array instead of objects using .push (as suggested by #lanzz), then $.inArray will work as you expect.
Alternatively, if you do need to store objects within the array (if for example you need to have multiple properties within each object) you would need to iterate over each object and see if the colName already exists:
var colExists = false;
var text = $(this).text();
$.each(columnModel, function(k, v) {
if(text == v['colName']) {
colExists = true;
}
});
Then change your check from if(colExists === -1) to if(!colExists).
Example
$(function () {
$('#ddlMain').change(function (event) {
$('option:selected', $(this)).each(function () {
var colExists = false;
var text = $(this).text();
$.each(columnModel, function(k, v) {
if(text == v['colName']) {
colExists = true;
}
});
if(!colExists) {
columnModel.push({'colName': $(this).text()});
alert($(this).text() + ' added to columnModel');
}
});
});
});

Dereferencing a variable to its value to use in another function javascript

function get_event_ids_from_dom()
{
var event_ids = {};
$.each(
$("td.ms-cal-defaultbgcolor a"),
function(index,value){
var str = new String(value);
var id = str.substring(str.indexOf('=')+1,str.length);
if(typeof(event_ids[id]) == "undefined")
{
event_ids[id] = this;
}
else
{
**event_ids.id.push(this);**
}
}
)
return event_ids;
}
In above javascript event_ids is a hashtable. I am trying to assign values to this hashtable.
A hashtable can be added with multiple values using "hashtable.key.push(value)". I am trying to do this using event_ids.id.push(this); in the above code.
I have declared "id" as a variable in the code. The problem is, I am not able to dereference variable "id" to its value.
Is this possible in jquery/javascript?
Example use of hashtable:
event_ids = {};
event_ids["1"]= 'John';
event_ids.1.push('Julie');
The above example would add john and julie to hash table.
Try this instead:
function get_event_ids_from_dom() {
var event_ids = {};
$.each(
$("td.ms-cal-defaultbgcolor a"),
function(index,value){
var str = value.toString();
var id = str.substring((str.indexOf('=') + 1), str.length);
if(typeof(event_ids[id]) == "undefined") {
event_ids[id] = [];
}
event_ids[id].push(this);
});
return event_ids;
}
Please, note that while object["id"] is the same as object.id, object[id] is not.
Nicola almost had it:
if(typeof(event_ids[id]) == "undefined") {
event_ids[id] = [];
}
event_ids[id].push(this);
Also please read the comment I left for your question.
In my opinion event_ids is an object (there are no hastables in javascript, just either indexed arrays or objects).
What you are tring to do is using push (an array method) on something that is not an array so i think you must change something:
you could try:
if(typeof(event_ids[id]) == "undefined")
{
event_ids[id] = [];// the property id of object event_ids is an array
event_ids[id].push(this);
}
else
{
event_ids[id].push(this);
}
It should work

Categories