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-]')
Related
I have some JSON data that I am retrieving from https://status.mojang.com/check and am storing in a variable. I'm still quite new to JSON/JS and I can't seem to find any answers on google.
Code:
function checkMojang() {
var mojangStatus = mojang.status();
mojangStatus.then(function (message) {
var response = JSON.parse(message);
})
}
Data I am using can be seen at the link above. I am trying to check all the data in the json array, see if any of the values contain "yellow" or "red" and get the keys for those values along with their checked value but can't figure out how to do so.
You can loop through the array and then through the object properties and make a new object using the colors as keys
var response = [{"minecraft.net":"green"},{"session.minecraft.net":"red"},{"account.mojang.com":"green"},{"auth.mojang.com":"green"},{"skins.minecraft.net":"green"},{"authserver.mojang.com":"yellow"},{"sessionserver.mojang.com":"green"},{"api.mojang.com":"green"},{"textures.minecraft.net":"green"},{"mojang.com":"red"}];
var new_response = {};
response.forEach(function(obj){
for (var prop in obj) {
if(obj.hasOwnProperty(prop)) {
if(new_response[obj[prop]] == undefined) new_response[obj[prop]] = [];
new_response[obj[prop]].push(prop);
}
}
})
console.log(new_response);
The you can use the object for your needs as
new_response["red"]
giving you the list of all key with red value.
you can use the method array.foreach() to execute a provided function once per array element and the for ... in to itarate over the enumarable properties.
So you can test the value and get keys for the value "yellow" or "red"
response.forEach(function(element) {
for (k in element) {
if (element[k]=="red" or element[k]=="yellow") {
// k is the key
}
}
});
function checkMojang() {
var mojangStatus = mojang.status();
mojangStatus.then(function (message) {
var response = JSON.parse(message);
for (i = 0; i < response.length; i++) { // iterate over response array
var item = response[i]; // get item from array
var key = Object.keys(item)[0]; // get the key of the item
var value = item[key]; // get the value of the item
if (value === 'yellow' || value === 'red') {
// do something, like adding it to a list
}
}
});
}
I have a function that checks for a div, and if it exists it fills it with the matching data from a JSON array. The Div and the data have the same id & key, so I want to be able to put those in a string for a more elegant solution. However, the final element of trying to apply the string element to the data key doesn't seem to be working. I get "Cannot read property '0' of undefined"
Original code:
$.getJSON('myDataUrl', function(data) {
if ($("#title").length){document.getElementById("title").innerHTML=data.title};
if ($("#noun").length){document.getElementById("noun").innerHTML=data.noun};
if ($("#_id").length){document.getElementById("_id").innerHTML=data._id};
if ($("#owner_id").length){document.getElementById("owner_id").innerHTML=data.owner_id};
});
The more 'elegant' solution I'm trying to reach:
$.getJSON('myDataUrl', function(data) {
var contentString = "name,noun,_id,owner_id";
var splitContent;
splitContent = contentString.split(",");
for(i = 0; i < splitContent.length; i++)
{if ($("#" + splitContent[i]).length){
document.getElementById(splitContent[i]).innerHTML=data.splitContent[i];
};
}
Looks like should be enough:
$.getJSON('myDataUrl', function (data) {
for (var k in data) {
$("#" + k).html(data[k]);
}
});
The problem is data.splitContent[i]. That should be data[splitContent[i]]. That is, you want to use the current key (e.g. name) as a key in the data object.
You could also use jQuery's Map.
$.map(data, function(value, key) {
$("#" + key).html(value);
});
Here's the working JSBin : http://jsbin.com/tocege/2/edit?html,js,output
I am new to localStorage. I set array in localstorage so how can get this value. My code as below.
$scope.lineItemID = data.id;
var itemtemp={
"itemid": data.id,
"qty": $scope.quantity
};
var itemqty=JSON.parse(localStorage.getItem("itemqty")) || [];
itemqty.push(itemtemp);
localStorage.setItem("itemqty", JSON.stringify(itemqty));
So my question is how can I get itemqty.qty as per itemid from localstorage
try Below code
$.each(data.itemqty, function(index, item) {
// append data using html //use item.name
});
OR try below
$.each(data, function(idx, item){
// append data using html
//
});
You are quite simply creating an array of objects itemqty and saving it in the browser's storage. When you do this:
var itemqty=JSON.parse(localStorage.getItem("itemqty")) || [];
//itemqty is available to you as an array of objects.
Suppose you are looking for the associated quantity for some itemid stored in the variable foo. You just need to traverse the parsed itemqty like so:
$.each(itemqty, function( index, value ) {
if(value.itemid == foo)
{
console.log(value.qty);
// value.qty is the required quantity
}
});
items=JSON.parse(localStorage.getItem('itemqty'));
for (var i = 0; i < items.length; i++) {
if(items[i].itemid === itmId) {
return items[i].qty;
}
}
I am using it & it's working
EDIT 2
Check the fiddle - http://jsfiddle.net/SN5zT/2/
Following is the fiddle for which I am not sure why I am getting undefined in dropdown.
My fiddle - http://jsfiddle.net/z6GDj/
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try {
var sportPositionOptions = '';
var parsedJson = JSON.parse(res);
var allSportPosition = parsedJson.allSportPosition;
var values = new Array();
$.each(allSportPosition, function (index, value) {
values[index] = value;
});
//alert(values.length);
values.sort();
$.each(values, function (atIndex, atValue) {
sportPositionOptions = sportPositionOptions + '<option value="' + atIndex + '">' + atValue + '</option>';
});
$(sportPositionOptions).appendTo("#player");
} catch (e) {
alert("Parsing error:" + e);
}
$.each is automatically sorting keys to 25,26,27,28 for res.
Please explain the reason of this and why I am getting undefined ?
Let me know If i need to explain it more, I will surely do it :)
EDIT
Please explain the reason why it is getting sorted automatically http://jsfiddle.net/SN5zT/
Try
values.push(value);
instead of
values[index] = value;
Fiddle Link
The following script is working, I also figured out where the "undefineds" came from.
http://jsfiddle.net/z6GDj/3/
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try{
var sportPositionOptions = '';
var parsedJson = JSON.parse(res);
var allSportPosition = parsedJson.allSportPosition;
var values = allSportPosition;
//$.each(allSportPosition, function(index, value) {
// values[index] = value;
//});
//alert(values.length);
$.each(values,function(atIndex, atValue){
sportPositionOptions = sportPositionOptions+'<option value="'+atIndex+'">'+atValue+'</option>';
});
$(sportPositionOptions).appendTo("#player");
}
catch(e){
alert("Parsing error:"+ e);
}
The array is sorted automatically, because the keys are set correctly.
see http://www.w3schools.com/js/js_obj_array.asp. "An array can hold
many values under a single name, and you can access the values by
referring to an index number."
Or: Change the index, and you´re changing the order. (index indicates the order).
The undefined values are created by javascript default, check the last answer in here (How to append something to an array?)
"Also note that you don't have to add in order and you can actually
skip values, as in
myArray[myArray.length + 1000] = someValue;
In which case the values in between will have a value of undefined."
Since you are passing an object to each(), jquery passes the key as the index parameter. In your object, the keys are ranged from 25 to 28. Setting the array using the values[25] on an empty array will expand the array to index 25, with the first 25 elements undefined. Using values.push(value) will append the value at the end of the array.
$.each is doing the following assignment that is why you are getting so many undefined
values[25] = "Forwards (Strickers)"
values[26] = "Midfielders"
values[27] = "Fullbacks (Defenders)"
values[28] = "Goalkeeper"
During $.each browsers will automatically sort the keys if the keys are integer, one way to avoid this is use non integer keys
What you need to do is define your options before you sort them , and then append them to your select:
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try {
var sportPositionOptions = '',
parsedJson = JSON.parse(res),
allSportPosition = parsedJson.allSportPosition,
options = new Array();
$.each(allSportPosition, function (index, value) {
options[index] = $('<option></option>', {
value: index,
text: value
});
});
$.each(options, function (index) {
$('#player').append(options[index]);
});
} catch (e) {
alert("Parsing error:" + e);
}
jsfiddle: http://jsfiddle.net/z6GDj/11/
Given the following HTML form:
<form id="myform">
Company: <input type="text" name="Company" value="ACME, INC."/>
First Name: <input type="text" name="Contact.FirstName" value="Daffy"/>
Last Name: <input type="text" name="Contact.LastName" value="Duck"/>
</form>
What is the best way serialize this form in javascript to a JSON object in the format:
{
Company:"ACME, INC.",
Contact:{FirstName:"Daffy", LastName:"Duck"}
}
Also note that there might be more than 1 "." sign in the field name.
I think that what you'd do is this: for each input, first split the name at the separators (the '.' characters). Now, you have an array of names. You can then iterate through that array, making sure that your target "assembly" object (and sub-objects) have containers every time you come across a new name segment. When the array has 1 element in it, you simply add the value.
$.fn.extractObject = function() {
var accum = {};
function add(accum, namev, value) {
if (namev.length == 1)
accum[namev[0]] = value;
else {
if (accum[namev[0]] == null)
accum[namev[0]] = {};
add(accum[namev[0]], namev.slice(1), value);
}
};
this.find('input, textarea, select').each(function() {
add(accum, $(this).attr('name').split('.'), $(this).val());
});
return accum;
});
// ...
var object = $('#myform').extractObject();
I just sort-of made that up so there might be a bug or two; I can't remember whether all the browsers have "slice" but I think they do.
(edit: I forgot the all-important call to split())
You can loop through the form fields by name, use String#split to split the names on dot, and build up your resulting structure. Concept code:
function serializeDeep(form) {
var rv, obj, elements, element, index, names, nameIndex, value;
rv = {};
elements = form.elements;
for (index = 0; index < elements.length; ++index) {
element = elements[index];
name = element.name;
if (name) {
value = $(element).val();
names = name.split(".");
obj = rv;
for (nameIndex = 0; nameIndex < names.length; ++nameIndex) {
name = names[nameIndex];
if (nameIndex == names.length - 1) {
obj[name] = value;
}
else {
obj = obj[name] = obj[name] || {};
}
}
}
}
return rv;
}
Note that that doesn't allow for fields with repeated names (which should create arrays), nor does it elegantly handle a situation where you use the names "foo" and "foo.bar". But it should get you started.
I have managed it this way:
$('#Myform').attr('onsubmit', 'test()');
function test() {
var obj = {};
obj.title =$('#title').prop('value');
console.log('title: '+obj.title);
obj.website =$('#website').prop('value');
console.log('website: '+obj.website);
obj.tags =$('#tags').prop('value').split(',');
console.log('tags: '+obj.tags);
do_something(JSON.stringify(obj));
}
Of course this can be done if you know what the names are, and I am in fact generating the table itself using Formation plug-in.
I created an example for this question by using plain js, please check developer tool console to see the data object!
jsfiddle example
var data = {};
var array = 'person.name.first'.split('.');
var value = 'myFirstName';
generateObj(data, array, value);
console.log(data);
function generateObj(obj, arr, val) {
if (arr.length === 1) {
obj[arr[0]] = val
return;
}
var restArr = arr.splice(1);
if (!obj[arr[0]]) {
obj[arr[0]] = {};
}
generateObj(obj[arr[0]], restArr, val);
}
solution:
transform each name string to array.
iterate through each array.
recursively call a method which create an obj and set this obj as the value of the property and pass this obj to the next recursion.
Create an object of that shape then use a JSON encoder to write it out.