Problem with converting array to json in JavaScript - javascript

I have this code:
var fields = [];
$('input').each(function(){
var name = $(this).attr("name");
fields[name] = $(name).val();
});
And I want convert the fields variable to a json string, but when I use JSON.stringify I get (using console.log) only: []
How can I simply convert array fields to a json string?

Ok problem was on the following line:
fields[name] = $(name).val();
I changed name to this:
fields[name] = $(this).val();
And worked like i want it to.

If you want text strings like field names (as opposed to numbers) as property names, you want an object, not an array. Initialize fields to {} instead of [].
The JSON serialization of an array will only include the properties whose keys are numbers, from zero up to the value of .length (minus one).

Just made one correction, use object instead of array:
var fields = {};
$('input').each(function(){
var name = $(this).attr("name");
fields[name] = $(name).val();
});

Related

how to save values of select options in javascript using e.target.value

I gave some options some values in html and I want to save these values in a js var and I wrote the following line but it didn't work
for (let node of document.getElementsByClassName('op.e.target.value')) {
values.push(node.value);
}
(where op is the class given to all the values)
Firstly, getElementsByClassName accepts class names as its argument only, not a function name in a string
When you're using getElementsByClassName you're storing an array of html elements, so to get the values of each you would need to for loop through it.
var values1 = document.getElementsByClassName('op');
var values = [];
for (let node of values1) {
values.push(node.value);
}

accessing values form string in jquery

I am returning string from database in following
format =opRadio=1&selSchool=0&opRadio2=1&selClg=0
What I want to access values like 1 or 0 in javascript or jQuery. I mean I want to retrieve 1 when I pass opRadio.
I tried by encoding string into json but no luck.
Thanks in advance.
Try this :You can use split('&') to seperate key value pair and then use split('=') to get key and value to put it in map. use map to retrieve values by passing key
var dbString = "opRadio=1&selSchool=0&opRadio2=1&selClg=0";
dbString = dbString.split('&');
var map = {};
for(var i=0;i<dbString.length;i++)
{
var keyValue = dbString[i].split('=');
map[keyValue[0]] = keyValue[1];
}
//to read value by passing key
alert(map['opRadio']);

separate values of a textbox and place it on an array in javascript

I have a textbox in which a user its going to input a value which I want to take and do the following. I want to be able to separate each word and add something to the end of them. so if they put 123. I want to separate it and make it 1.jpg, 2,jpg 3.jpg
after they are separated i want to put it in an array to compare to another array and go from there.
Here is what I got so far
<input type="text" id="textfromuser" />
<script type = "text/javascript">
function validate(){
var lists = [];
var VAlidation = document.getElementById("textfromuser").value;
lists.push(VAlidation);
for(var i=0; i<lists.length; i++)
alert(lists[i]).split('.');
this part of the code was to show that the value in the textbox is split and placed in an array but its not working.. any ideas?
I think you are confusing arrays and strings, the value you obtain from the input is a string and you're afterwards adding it to the lists array and iterating over that array.
May be this is what you were looking for
HTML
<input type="text" id="textfromuser" />
Javascript
function validate(){
// empty array
var ar = [];
// obtain a string from the input "text" field, retrieved by the "id" attribute
var VAlidation = document.getElementById("textfromuser").value;
// split the string into a character array
var lists = VAlidation.split('');
// iterate over the character array
for(var i=0; i<lists.length; i++){
// create a string concatenating the array's element and '.jpg'
var str = lists[i]+'.jpg';
// add the string var to the array
ar.push(str);
}
return ar;
}
I created a jsfiddle to test it quickly if you want a try
http://jsfiddle.net/kpw23/2/
UPDATE
To compare arrays there are many ways to accomplish it. A simple way to achieve this would be to serialize the arrays and compare the serialized strings:
// having two arrays
var list = ['1.jpg','2.jpg','3.jpg'];
var list2 = ['1.jpg','2.jpg','3.jpg'];
// "Serialize" the arrays, the join() method
/// joins the elements of an array into a string, and returns the string
serlist = list.join();
serlist2 = list2.join();
// Compare both serialized arrays
if(serlist==serlist2){
alert("Arrays are equal");
}
else{
alert("Arrays are not equal");
}
This method will only work if the arrays are sorted the same way and contain exactly the same entries in the same array positions.
Your alerting the value of lists[i], not lists[i].split('.'). Try:
alert(lists[i].split('.'));

JS: name/val pairs to array

I'm using a one-off language similar to javascript in syntax, so an answer in that more common language should suffice.
I have a list of name/val pairs that i built from a big GET string that looks something like
"n1=v1,n2=v2..."
I'm not sure that my initial approach is correct. I used a primitive in this language
tolist(GETstring,"=")
to split the name value pairs into the above list. Perhaps, this is the wrong approach from the gate.
This gives me
data = [["n1","v1"],["n2","v2"],...]
I'm trying to change this into a named array, such as
data["n1"]="v1";
data["n2"]="v2";
...
so that I can access items by name, not by list index (as it is highly volitale)
What is the better approach to getting the data in this format. I've tried a few including evals but nothing seems to work.
You'll have to split the string up then iterate through it.
var obj = {};
var originalString = "n1=v1,n2=v2";
var splitOriginalString = originalString.split(",");
for (var i = 0; i < splitOriginalString.length; i++) {
var tmpObj = splitOriginalString[i].split("=");
obj[tmpObj[0]] = tmpObj[1];
}
There is no option to do it. You've got two ways to do workaround.
Create two arrays, one for keys and one for values.
var indexes = ["test", "test2"];
var values = ["val", "val2"];
var value = values[indexes.indexOf("test2")]; // will get "val2"
Create nested array with key 0 for your string key and with 1 for its value.

How do I get all spans created in my HTML page using jQuery

I'm getting all input texts in my HTML page by using this:
var inputs = data.context.find(':input');
$('#result').text(JSON.stringify(inputs.serializeArray()));
Then I have an JSON string with id and value of each input text.
I'm trying to do something similar but with all my spans. I have this in my HTML file:
<td class="name"><span>{%=file.name%}</span></td>
I can have as many <td class="name"> ... tags as I want. So I have to get the value of all of them and convert to an JSON string as I did with the input text above.
How can I do it?
this code snippet: $('.name span') will return an array of objects, so in order to get the text from each one you need to run on it as an array:
$('.name span').each(function(index,val){
//do something with val
});
you can see a reference to this method here.
Simple fiddle: http://jsfiddle.net/CMdBa/1/
Iterate over .name (or specifiy deeper if necessary), build your data structure (using data), and then convert it to JSON. Working example: http://jsfiddle.net/tLuPC/
Below is simulating id if you needed to obtain that as mentioned in your post. Using data- attribute to store info. Otherwise you can simply just obtain the name.
var data = [],
jsonData = null;
$('.name').each(function () {
var item = $(this);
data.push({
id: item.data('id'),
name: $('span', item).text()
});
});
jsonData = JSON.stringify(data);
console.log(JSON.stringify(jsonData));
You can use a map function to enumerate and format a collection.
var spanTextArray = $('td.name span').map(function(){
return $.trim(this.innerHTML);
}).get();
This will output an array of file names, you could easily modify the return to output an array of key value pairs.

Categories