Get jQuery element by stored data - javascript

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);

Related

Search in an Object Array with more than one condition jQuery grep()

I have an Object Array with Key-Value pair on jQuery like this
And I am searching in these arrays to find a match with with an id that I will provide so I have
var result = $.grep(records, function(e){ return e.id== id; });
So this looks like, search a record in the array with an id of whatever the value of id that i passed it. It works fine but what if I want to pass two parameters to match the records in the array? let's say columnheader and parent_colheader? What will my previous
var result = $.grep(records, function(e){ return e.id== id; });
syntax should be?
Use multiple variables with &&
var id = 1;
var columnheader = 'test';
var parent_colheader = 'test';
var result = $.grep(records, function(e) {
return e.id == id && e.columnheader == columnheader && e.parent_colheader == parent_colheader;
});

find data attribute by part of name

How can I get a value of data attribute by part of name?
For example:
<div data-pcp-email="some text" data-pcp-order="some int" data-ref="some data"></div>
And suppose, I want to get all data attributes begin with data-pcp-: the result must bedata-pcp-email and data-pcp-order
You can get all the attributes (and their values) where the attribute name beings with 'pcp' like below:
// get an object map containing all data attributes
var data = $('selector').data();
// filter out what you need
for(var key in data) {
if(key.indexOf('pcp') === 0) { // attrib names begins with 'pcp' ?
console.log(key + ' => ' + data[key]);
}
}
Here's a demo: http://jsfiddle.net/8waUn/1/
If you only set the attribute with the HTML or with jQuery attr function:
$('div[data^=pcp-]')
If you set the value with jQuery's data function, you will have to use filter.
$('div').filter(function(){
var data = $(this).data();
for (var key in data){
return key.indexOf('pcp-') === 0;
}
});
If you want only the attributes you can use map:
var values = $('div').map(function () {
var data = $(this).data();
var results = [];
for (var key in data) {
if (key.indexOf('pcp') === 0) results.push({
key: key,
value: data[key]
});
}
if (results.length)
return results;
}).get();
console.log(JSON.stringify(values));
Live DEMO
Use the "attribute begins with" jQuery selector:
$('div[data^=pcp-]')

How to create array in jquery

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();

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');
}
});
});
});

jQuery to Select elements that does not contain a certain value

I am using the following jQuery code to count the number of text fields that have a value that is the same as its title attribute.
$(".textfield").val( $(".textfield").attr('title') ).size();
Problem: How do I count the number of text fields that do not have a value equal to its title attribute?
First of all, the code you post is not doing what you say it does. This:
$(".textfield").val( $(".textfield").attr('title') ).size();
Will set the value of all elements with class ".textfield" to the title of the first ".textfield" element's title attribute, and then return a count of all of them.
You need to compare the return of the .val() method (with no parameter it returns the current value) with the return of the .attr('title') method. You can do this with .filter() and then check the .length of the resulting jQuery object:
$('.textfield').filter(function() {
var $this = $(this);
return $this.val() == $this.attr('title');
}).length;
And then to get a count of those where the value is not equal just do the same thing except with != instead of ==. So:
$('.textfield').filter(function() {
var $this = $(this);
return $this.val() != $this.attr('title');
}).length;
(Note that .length will give you the same count as .size() but without the overhead of a function call.)
I would use filter() and then access the length property of the returned set.
var count = $('.textfield').filter(function() {
return $(this).val() != $(this).attr('title');
}).length;
You could also probably get away with the body of filter() as return this.value != this.title.
use the filter function.
use length property of the selector
var length = $('.textfield').filter(function() {
return this.value != this.title;
}).length;

Categories