I am using something similair to this:
$("input").each(function(number,element)
{
var inputField=$(element);
if(inputField.data("FieldLocalizationStrings") == null)
inputField.data("FieldLocalizationStrings", []);
}
And to add data:
var data=inputField.data("FieldLocalizationStrings");
data.push({Language:inputField.attr("language"),Value:inputField.val()});
But when i try to retreive, it seems to ignore on which DOM element it has been saved and just loads it like it was all saved on the same element. Anyone an idea why this would happen? i have used the same technique before and it proved to work, but now i can't figure out why this is hapening.
I confirmed it does not save it to multiple input fields, but when loading it acts like it is.
Update
Added a fiddle here
$("input").each(function(number,element)
{
var inputField=$(element);
if(inputField.data("FieldLocalizationStrings") == null)
inputField.data("FieldLocalizationStrings", [
{
Language:inputField.attr("language"),
Value:inputField.val()
}
]);
//If later you want to append to the data
inputField.data("FieldLocalizationStrings").push({/* Your data */})
}
http://api.jquery.com/jQuery.each/ - as for documentation you'll get value as second parameter. If you want set data for an element you should use this.
Related
I'm learning JS and i'm trying to make a little app with node.js with JSON on.
I managed to get what I wanted in my json and put it in my html as input, with the json data as "value". When I click on the elements, we can change each of them, since they are inputs, and so I change their "value". Until then, everything works, but when I modify my 1st element of the list, all the elements are modified in the json...
And only the first element in my HTML changes my json, the others don't, they change but don't register in the json, and I have trouble understanding why.. I tried forEach and this.el but nothing works, it doesn't understand my data..
There is the code
var newValue = $("#snippetTitle").on("change paste keyup", function () {
if (newValue.val() != $("#snippetTitle:input")) {
for (var i = 0; i < jsonParse.snippets.length; i++) {
newValueTitle = jsonParse.snippets[i].title = newValue.val();
writeValue = JSON.stringify(jsonParse, newValueTitle);
fs.writeFileSync('save/snippets.json', writeValue, 'utf8');
}
} else {
}
});
Thank you for explaining to me how I could do so that each element could be modifiable, and especially that it is recorded in the json...
I'm not looking for complete solutions, just help to understand what to do.
I'm trying to write a script that retrieves data from JSON using jquery. I searched the downloaded array. How to find the value to perform any operation.
I pull out the data using getJSON and everything works. But I'm having trouble finding the search. Can anyone help me? This data from JSON:
[{"id":"10","data":"12345"},{"id":"11","data":"6666"}]
The simplest way to search through an array would be....
var data = [{"id":"10","data":"12345"},{"id":"11","data":"6666"}];
for(var row in data)
{
var item = data[row]; //This is the object {id:..., data:...}
if(item.id == ...) //Use if statement to search for data
{
//do something here when data is found
}
}
When I store data returned from a service in my controller and then edit it, it also changes the data in the service.
JSFiddle Demo
/* The backend connection part and the actual markdown editor JS have been removed because it would just make the code huge and is irrelevant to the problem */
var myApp = angular.module('myApp', []);
// In my app, this service caches blog post data from my server on the client side and returns single posts from it
myApp.factory('PostService', function ($log, $filter, $http) {
var data;
// Just an example for data pulled from server
data = [{
id: 99999,
text: "Hello"
}];
// Function for returning a post out of the data array loaded from the server
var getData = function (id) {
if (id !== undefined) {
var arr = $filter('filter')(data, {
id: id
});
if (arr.length === 0) {
$log.error('PostService:: getData(' + id + '):: Post Not Found');
return 'not_found';
} else {
$log.debug('PostService:: getData(' + id + '):: Post returned');
return arr[0];
}
} else {
return data;
}
};
return {
getData: getData
};
});
function ctrl($log, $scope, PostService) {
var edit = this;
// Sample post id
edit.editingId = 99999;
// "Copy" (apparrently more "bind") the blog post data to edit.data
edit.data = PostService.getData(edit.editingId);
}
This is used for a markdown editor. I wanted to load the data from the service into the controller, then edit it, and give the service the new version on pressing a "Save" button.
If the aforementioned behaviour is correct in the sense of Angular's databinding, what is a better solution to achieve what I want?
Update
Based on PSL's comment and Thibaud Sowa's answer I changed the getData() function to return a copy using angular.copy(). However, it seems not to be possible to copy one object out of an array (like angular.copy(arr[0])), as it will still return the whole array. See the updated JSFiddle.
Update 2
Well, I was dumb. I corrected it in the fiddle. Thank you for your answers.
This is because you are returning an object. In javascript when you do that it's like if you are passing a pointer.
You should use angular.copy to copy the object field by field, like this:
return angular.copy(data);
See the doc here https://docs.angularjs.org/api/ng/function/angular.copy
Response to your update
Well, I edited your fiddle, to show you that you can copy an item of an array. Actually it's seems that every thing works like you want... (Or I didn't understand your need!)
The updated fiddle:
https://jsfiddle.net/thibaudsowa/aybLwa2L/3/
There is a very simple solution to your problem:
If you dont want to change the data you get from the service make a copy
There are plenty of threads on SO discussing the fastes or most elegant way to deep copy a Javascript object. A simple and rather fast solution is using json parse and stringify like this:
var copyOfA = JSON.parse(JSON.stringify(a));
Apply this to the data you get from your service and you are good to go :)
I've seen other posts in this site regarding the same issue and I've tried the solutions given. I've also visited the links that may offer a solution but I'm still stuck with the same error.
I'm using DOJO and something as simple as this won't even work
myStore.newItem({id: 'test', otherfield: 'otherinfohere'});
myStore.save();
Supposedly the "newItem() was not passed an identity for the new item" error appears when you haven't provided an identifier for the new item, which i have.
The whole purpose of this (Just in case anyone can provide a good idea or has done something similar before) is that i want to create a data grid that shows info from a particular store. The problem is, that in that store all the items may not have the same structure. For instance:
I may have a store that looks like this
{identifier: 'id',
label: 'name',
items: [
{ id:'1', name:'Ecuador', capital:'Quito' },
{ id:'2', name:'Egypt', capital:'Cairo' },
{ id:'3', name:'El Salvador', capital:'San Salvador' , additionalField: 'otherinfohere'},
{ abbr:'gq', name:'Equatorial Guinea', capital:'Malabo', additionalField: 'otherinfohere'},
]}
This is possible because I'm the one constructing the store in a Spring Controller (I'm also using the Spring Framework) from information I have locally stored in a Berkeley DB. So what i need is a data grid with a dynamic layout because I don't want blank spaces to show in the view in the rows with lesser amount of fields, and i need to show all the info in the store at the same time, but i don't know how to do this.
I thought of doing it by creating a simple layout of only 1 field. In it I would load data from a store i create dynamically at runtime. The data in the store would be composed of HTML combined with the values coming from the original store so I could obtain something like this, which is inside an attribute of a JavaScript Object and let the browser parse it for me:
<div><span>id: originalID </span>....</div>
This of course is a simple example, the html layout i'm looking for is far more complicated, but i think that passing it as a string to an object might do the trick.
The problem is that i don't even know if that idea will work because i get that error whenever i try to add values to my secondary store.
rdb.modules.monitor.historicStore.fetch({onComplete: function(items, request){
for (var i = 0; i < items.length; i++){
var item = items[i];
var obj = new Object();
obj.id = rdb.modules.monitor.historicStore.getValue(item, "id");;
var html = "<div><span>";
html += rdb.modules.monitor.historicStore.getValue(item, "sql");
html += "</span></div>";
obj.html = html;
myStore.store.newItem(obj);
}
}});
In this context "historicStore" refers to the JSON store that has the values that i need to convert and add to "myStore" after i added some HTML.
I hope you got the main idea of what I'm trying to do. If anyone can help me we either of these problems i would really appreciate it. Thanks in advance
For the issue regarding store:-
"id" is mandatory for a store, if it is going to be used for a grid(datagrid, EnhancedGrid, etc. whatever). The items are handled only on basis of "id" attribute by the grid data structures.
Usually, id can be a loop variable/ auto incrementation, to avoid any cases like you have said. Before adding the store to the grid, ensure that all items have the id attribute. You can write a function which will loop through each item and check for this, else add an auto-incrementing value for the id attribute of that item.
I have returned a form with some key value pairs populated. Depending on user interaction I want to insert some of them into my HTML. I have found some answers using AJAX but could not workout how to access the key value pairs via javascript. I do not want to use jquery yet as I want understand how javascript and the DOM works first. Below is an idea of what I want to do
<script>
function changeanchor(urlitem) {
document.getElementById("urlanchor").innerHTML = "";
while ($urls as $url) {
if (urlitem == $url->item) {
document.getElementById("urlanchor").innerHTML .= $url->urlanchor;
}
}
</script>
I know "$urls as $url" etc is PHP but I thought it was the easiest way to explain what I need to do.
I use PHP to generate the function call but I am unable to get it to display here it (pieces of code do not display)
Like so?
<script>
function changeanchor(urlitem) {
document.getElementById("urlanchor").innerHTML = "";
for (i in urls) {
var url = urls[i];
if (urlitem == url.item) {
document.getElementById("urlanchor").innerHTML += url.urlanchor;
}
}
</script>
urls was never defined so this code won't execute unless urls stores a bunch of url objects with those properties.
In order to create a url object that acts like the one you try to use, either use JSON to pipe it to the JavaScript or make an object:
var urls = [
{
'item': 100,
'urlanchor': 'foo'
}, {
'item': 200,
'urlanchor': 'bar'
}
];
are you asking about the setting key value pair data in a dome object then,
$('body').data('foo', 52);
link for help:-
http://api.jquery.com/data/