How to populate a dropdown box with jQuery from a JSON string? - javascript

I have a json object stored as a JavaScript string var containing both names and values for populating a dropdown box, say #dropdown. My question is, how can I access each element as value/label pairs and put them into a dropdown?
The json string looks like this:
[{"name":"Name1","value":"Val1"},{"name":"Name2","value":"Val2"}]
Does this need to be further parsed in any way?
I tried something like (but did not work)...
$(json).map(function () {
return $('<option>').val(this.value).text(this.name);
}).appendTo('#copy_input');
In what way do I need to further format my json to be able to easily iterate and fill the dropdown?

Can you try below and see if this works?
$(json).map(function () {
var elem = $('<option>').val(this.value).text(this.name)
elem.appendTo('#copy_input');
return 0; // dummy statement. You should be able to skip this statement too.
});

Related

Extract JSON table from JSON string element

I get this JSON in response from server:
{
"tab":[
"[[\"2018\",11,\"19\",\"16\",\"13\"],null,null,null,null,null,\"40\"]",
"[[\"2018\",11,\"19\",\"16\",\"19\"],null,null,null,null,null,\"56\"]",
"[[\"2018\",11,\"19\",\"16\",\"21\"],null,null,null,null,\"57\",null]"
]
}
I know, that I can get first element of tab table returned using $.tab[1]. The returned element is a string that holds a table - first element of this table is another table holding a date. The question is what JSON Path expression should I use in order to extract year value from the inner table or one of those numbers at the end (40, 56, 57)?
I'm not sure what you mean when you say you can get the first element with $.tab[1]. Are you using jQuery? Even so, that doesn't seem to make any sense. Regardless, you can parse those inner tables and access them normally as arrays:
var results = {
"tab":[
"[[\"2018\",11,\"19\",\"16\",\"13\"],null,null,null,null,null,\"40\"]",
"[[\"2018\",11,\"19\",\"16\",\"19\"],null,null,null,null,null,\"56\"]",
"[[\"2018\",11,\"19\",\"16\",\"21\"],null,null,null,null,\"57\",null]"
]
};
// you can refactor this as a method for more convenient usage, this is just a demo
var row = JSON.parse(results.tab[0]);
// now you just have a multi-dimensional array, use it as normal
console.log(row[0][0]); //year
console.log(row[6]); //number

loop in JSON with undefined elements

I am trying to figure out how to retrieve the values of a json of which i do not know the number of elements.
Example:
my json can be something like
var json = ["fixelement1":"value1","fixelement2":"value2","fixelement3":"value3","variableelement4":"value4","variableelement5":"value5"]
or
var json =["fixelement1":"value1","fixelement2":"value2","fixelement3":"value3","variableelement7":"value7","variableelement8":"value8", "variableelementN":"valueN"]
the only thing that I know is that the first 3 elements are always the same.
I use .indexOf() to search a value in fixelement3. What I would like to do is, if I find the element, I would like to retrieve the name of all the following elements (which number is variable and that are unknown) and their values.
javascript or jquery would work for me, but I have no idea..
thank you in advance!
var json ={
"fixelement1":"value1",
"fixelement2":"value2",
"fixelement3":"value3",
"variableelement7":"value7",
"variableelement8":"value8",
"variableelementN":"valueN"
}
for(prop in json){
console.log('key ======> value', prop, '=====>', json[prop]);
}

how to construct JSON before submitting form using javascript

I have the following demo on jsFiddle. I would like to submit this form using javascript and send a JSON object back to my controller.
As you can see multiple rows can be added to the table and submitted. In my JSON data I would like to keep track of which checkboxes got clicked for which rows. So for example, based on the below screen shot:
I would like the JSON object to look like this:
{light:[{red:on}, {yellow:off},{green:on}], dark:[{red:off}, {yellow:off},{green:on}]}...
The code I came up with looks like this:
var jsonObject = {};
$('.input-row').each(function(index, row) {
var innerObject = {};
$(':checkbox', row).each(function(index, checkbox) {
innerObject[checkbox.name] = checkbox.checked ? 'on' : 'off';
});
var key = $('input[type="text"]', row).val();
jsonObject[key] = innerObject;
});
console.log(jsonObject);
// use jsonObject somehow
We're creating an empty object that will be our overall JSON object (called jsonObject).
Then we're iterating over each of the rows of inputs (I've added an input-row class to these so they can be selected easily).
For each row, we create another empty object (called innerObject), then iterate over its checkboxes. For each checkbox, we add a property to innerObject: the key is the name attribute/property of the checkbox, the value is on or off depending on the checked state. Finally, we get the value of the text input on that row to use as the key in jsonObject, and add the property to it.
Here's a working example of the above code.
The easiest way to serialize a form as JSON is to use jQuery's serializeArray()
JSON.stringify($('form').serializeArray());
You should build your own JSON string and then use jQuery.parseJSON() to do this loop all your tr elements in the table and collect the information you need.
The below code is a start for you according the html in fiddler.
var strJSON = '';
$("#blacklistgrid tr").each(function (i) {
if (i != 0)
{
var currentRow = $(this)
strJSON += "{ " + currentRow.find("input[name='shade']").val() +"[{red: currentRow.find("input[name='red']").is(":checked")} ] }";
}
});
var theJSON = jQuery.parseJSON(strJSON);
please check the correct format for JSON string and I could not check the code if it working but you can get the logic here.

Value returned by getcol function in jqgrid

I have a grid using jqgrid. I need to store the some data returned by the url:, in a local variable so that I can display it in the subgrid. For this I add that column as a hidden column in the main grid, which is of the format in json:
"Details":[{"Name":"ttt", "Quantity":"12"}] .
Then in the loadcomplete: function I save the value to a variable using
var griddata = $("#grid').getCol('Details', false);
Now when I access griddata[0], I get a object Object. I tried to parse it to get the values correctly, but to no avail. I tried:
griddata[0].Details.Name
or
griddata[0].Details.0.Name
or
griddata[0].Name,
but all failed. I guess I am missing the format if the data returned by the getcol() function.I looked up the documentation on the method and it says that it returns just the values when we specify false, but could not get any examples.
If there are any examples or if there are any pointer to the solution, it will be greatly appreciated.
If you check the type of griddata[0] (for example with typeof operator) you will see that it has type of string - this is because the value you are getting is the result of toString() on the object you have passed. The reason for that is the way in which jqGrid is treating values.
If you want to store JSON as the value, you need to stringify it entirely:
"Details": "[{\"Name\":\"ttt\", \"Quantity\":\"12\"}]"
Now you can deserialize those string values into objects like this:
var griddata = $.map($("#grid").jqGrid('getCol', 'Details', false), function(value) {
return JSON.parse(value);
});
After that you can access the objects in the way you want:
var name = griddata[0].Name;
var quantity = griddata[0].Quantity;
As an alternative you can split your object into two columns, so the values can be accessed directly with getCol.

How to retrieve value from object in JavaScript

Hi I am using a Java script variable
var parameter = $(this).find('#[id$=hfUrl]').val();
This value return to parameter now
"{'objType':'100','objID':'226','prevVoting':'" // THIS VALUE RETURN BY
$(this).find('[$id=hfurl]').val();
I want to store objType value in new:
var OBJECTTYPE = //WHAT SHOULD I WRITE so OBJECTTYPE contain 400
I am trying
OBJECTTYPE = parameter.objType; // but it's not working...
What should I do?
Try using parameter['objType'].
Just a note: your code snippet doesn't look right, but I guess you just posted it wrong.
Ok, not sure if I am correct but lets see:
You say you are storing {'objType':'100','objID':'226','prevVoting':' as string in a hidden field. The string is not a correct JSON string. It should look like this:
{"objType":100,"objID":226,"prevVoting":""}
You have to use double-quotes for strings inside a JSON object. For more information, see http://json.org/
Now, I think with $(this).find('[$id=hfurl]'); you want to retrieve that value. It looks like you are trying to find an element with ID hfurl,but $id is not a valid HTML attribute. This seems like very wrong jQuery to me. Try this instead:
var parameter = $('#hfurl').val();
parameter will contain a JSON string, so you have to parse it before you can access the values:
parameter = $.parseJSON(parameter);
Then you should be able to access the data with parameter.objType.
Update:
I would not store "broken" JSON in the field. Store the string similar to the one I shoed above and if you want to add values you can do it after parsing like so:
parameter.vote = vote;
parameter.myvote = vote;
It is less error prone.

Categories

Resources