I'm new to Javascript. I need to split a string of this format:
["Man1","SKC2","fsdfds3","ETA4","Star5","SCity 6","TESTGB11"]
and create as options for select tag. I tried the below code
$.each(data, function (index, value) {
$('#bu_group').append($('<option/>', {
value: value,
text : value
}));
});
But I get strings split as letters.
What can I do to split the string to get options as
<option>Man1</option>
<option>SKC2</option>
Note : Some times this string may contain spaces as well.
If data is your string, then parse it from JSON to a JavaScript array of strings, then iterate over that:
var yourArray = JSON.parse(data);
$.each(yourArray, function(index, value) {
$('#bu_group').append($('<option/>', {
value: value,
text : value
}));
});
Try to pass the array first and then pass the translated array as the html string,
$('#bu_group').html($.map(JSON.parse(data),function(val,i){
return "<option value="+ val +">" + val + "</option>";
}));
DEMO
As data is actually coming from your server via ajax you can simply specify correct dataType.
Either
$.ajax({dataType: 'json', ...}).done(function(data){
//data will be parsed
});
Or
$.getJSON(url).done(function(data){
//data will be parsed
});
Or configure your server to return correct mime type (application/json)
if your data is
["Man1","SKC2","fsdfds3","ETA4","Star5","SCity 6","TESTGB11"]
then there is no problem, so I think you have your data as :
'["Man1","SKC2","fsdfds3","ETA4","Star5","SCity 6","TESTGB11"]'
which you must 'parse' it.
as you are using jQuery, one option is to parseJSON like this:
var parsed_array = $.parseJSON('["Man1","SKC2","fsdfds3","ETA4","Star5","SCity 6","TESTGB11"]');
after doing that, you can successfully do :
$.each(parsed_array, function (index, value) {
$('#bu_group').append($('<option/>', {
value: value,
text : value
}));
});
If you have your data as
var data=["Man1","SKC2","fsdfds3","ETA4","Star5","SCity 6","TESTGB11"]
then you can iterate this var, isn't it?
var data=["Man1","SKC2","fsdfds3","ETA4","Star5","SCity 6","TESTGB11"];
for(i=0;i<data.length;i++) {
$('#bu_group').append($('<option/>', {
value: data[i],
text : data[i]
}));
};
JSFiddle here
Related
I am trying to append JSON object to a select tag for future reference by using below code
$.each(actualData, function (key, value) {
var valueToAppend = [];
var vehicleId = value._id['$oid'];
var availableSeats = value.NumberOfSeats;
var item = {};
item["VehicleId"] = vehicleId;
item["AvailableSeats"] = availableSeats;
valueToAppend.push(item);
$('#vehicle_'+guid).append($('<option>', {value: '' + valueToAppend + '', text: '' + value.VehicleNumber + ''}));
});
It is appending values in browser like "value="[object Object]".
I want it should append like {VehicleId:"36ae8c855677879c88", AvailableSeats: "60"}. I want it should store id and number of seats. Please help!!!
You can store an object as a value of HTML element. So you have to store json string as a value
$('#vehicle_'+guid).append($('<option>', {value: '{VehicleId:' + valueToAppend.item.VehicleId+',AvailableSeats:'+valueToAppend.item.AvailableSeats+ '}', text:value.VehicleNumber}));
Try this . I am converting your Object to JSON String
$('#vehicle_'+guid)
.append($("<option></option>")
.attr("value",JSON.stringify(valueToAppend))
.text(value.VehicleNumber));
I want to fetch only 1st element of json array
my json data :
{
id:"1",
price:"130000.0",
user:55,
}
{
id:"2",
price:"140000.0",
user:55,
}
i want to access the price of 1st json element
price : "13000.0"
my code
$.each(data_obj, function(index, element) {
$('#price').append(element.price[0]);
});
but my output
is '1'
Assuming that you have array of objects
var arr = [{
id:"1",
price:"130000.0",
user:55,
},
{
id:"2",
price:"140000.0",
user:55,
}]
console.log(arr[0].price)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You data isn't valid JSON, JSON data key must be wrap within double quote, but your data isn't wrapped in double quote
var data = [{
"id":"1",
"price":"130000.0",
"user":55
},{
"id":"2",
"price":"140000.0",
"user":55
}]
console.log(data[0]["price"]);
Hello You just need to add [] from starting and ending point of your json string. see here var data = JSON.parse( '[{ "id":"1","price":"130000.0","user":55},{"id":"2","price":"140000.0","user":55}]');
var priceValue = 0;
$.each(data, function(index, element) {if(index == 0){ priceValue = element.price;}});console.log(priceValue);
Your answer will be 13000.0
The element having the your JSON data means, we can able to use below code to get the first JSON data.
element[0].price
Thanks,
You are using for each loop and in function you get 2 params first one is index and second is the element itself. So this will iterate through all elements.
$.each(data_obj, function(index, element) {
$('#price').append(element.price);
});
If you just want to get first element
$('#price').append(data_obj[0].price);
var my_first_json_obj = data_obj[0]; // Your first JSON obj (if it's an array of json object)
var my_price = my_first_json_obj.price; // Your price
$('#price').append(my_price);
If you want only the first item's price, you don't need a loop here.
$('#price').append(data_obj[0].price);
would work here.
For further reading you can refer here
Following is the solution worked for my problem
I use return false;
$.each(data_obj, function(index, element) {
$('#price').append(element.price[0]);
return false;
});
Which gives only 1st value of array elements.
I received a response from MY ajax as follows
"{\"analgesicTax\":false,\"unitPriceRequired\":false,\"toConsumer\":true,\"toRetailer\":true,\"taxName\":\"1\"}"
After calling JSON.parse(result), the result looks like
{"analgesicTax":false, "unitPriceRequired":false, "toConsumer":true, "toRetailer":true, "taxName":"1"}
Up until that point everything seems to be ok. However, when I tried to print my key/value pairs by using following code
var data = JSON.parse(result);
console.log(data);
console.log(data.analgesicTax);
for (var prop in data) {
console.log(prop+"is" + data[prop]);
I tried both using with and without JSON.parse() but the output is same as follows.
0is{
1is"
2isa
3isn
4isa
5isl
6isg
7ise
8iss
9isi
10isc
11isT
12isa
13isx
14is"
15is:
16isf
17isa
18isl
19iss
20ise
21is,
22is"
23isu
24isn
25isi
26ist
27isP
28isr
29isi
30isc
31ise
32isR
33ise
34isq
35isu
36isi
37isr
38ise
39isd
40is"
41is:
42isf
43isa
44isl
45iss
46ise
47is,
48is"
49ist
50iso
51isC
52iso
53isn
54iss
55isu
56ism
57ise
58isr
59is"
60is:
61ist
62isr
63isu
64ise
65is,
66is"
67ist
68iso
69isR
70ise
71ist
72isa
73isi
74isl
75ise
76isr
77is"
78is:
79ist
80isr
81isu
82ise
83is,
84is"
85ist
86isa
87isx
88isN
89isa
90ism
91ise
92is"
93is:
94is"
95is1
96is"
97is}
It seems to me that rather than treat it like a JSON object, it is handling as a string array. Any Inputs?
If the result is already JSON, then you don't want to use JSON.parse() since JSON.parse() converts a string representation of JSON into an object. Simply run your for loop as you coded and you should be able to get all the keys and their values.
However, if you do start out with a string representation of a JSON object, that's when you want to use JSON.parse().
//Starting with a JSON object
var result = {
"analgesicTax": false,
"unitPriceRequired": false,
"toConsumer": true,
"toRetailer": true,
"taxName": "1"
}
for (var prop in result) {
console.log(prop + " is " + result[prop]);
}
console.log('');
//Starting with JSON represented as a string
var result = "{\"analgesicTax\":false,\"unitPriceRequired\":false,\"toConsumer\":true,\"toRetailer\":true,\"taxName\":\"1\"}";
var data = JSON.parse(result);
for (var prop in data) {
console.log(prop + " is " + data[prop]);
}
try this.
var data = JSON.parse(result);
Object.keys(data).forEach(function (key) {
console.log(data[key]);
});
Note please. (I'm currently using the Spring Framework (MVC))
The value sent from Controller to ajax is ...
It looks like the picture above.
I am looping through the forEach statement for the values in that array, and I want to put the value into the tag.
So I wrote the code.
$(function()
{
$('#doctorSelect').change(function()
{
$('#selectGugan').show();
var doctor_idx = $(this).val();
$.ajax
({
type: 'POST',
url: 'selectDoctor.do',
data: {"d_idx":doctor_idx},
dataType: 'JSON',
success: function(sectionDate)
{
console.log(sectionDate);
var html = "<option value=''>Choice Doctor</option>";
var responseData = [];
responseData.push(sectionDate);
console.log(responseData);
$.each(responseData, function(key, value)
{
console.log("forEach statement in responseData :" + responseData);
//html+="<option value="+new_date+">"+new_date+"</option>";
});
$('#doctorSelect_2').html(html);
},
error: function(sectionDate)
{
console.log("data : " + sectionDate);
}
});
});
});
But unexpectedly, I do not get the key, value.
In fact, I don t know about the jquery forEach statement.
How do I set key, value?
I just want to bring those values and express it like this.
<option value="ri_idx">ri_startDate ~ ri_endDate</option>
How to set key, value or How to use jquery forEach statement ?
I am a beginner. I would appreciate it if you could give me an example.
In your case I am not sure why would you be doing this:
responseData.push(sectionData);
because this way you dont get an array of objects as I believe you thought you would, you simply will get an array with 1 element in it, which is many objects, so doing a forEach on that array will not help, because the value will be the multiobject element (not a single object that you could access properties).
What you want to do is iterate over your original objects, so your code should be something like this:
$.each(sectionDate, function(key, value){
// here you can access all the properties just by typing either value.propertyName or value["propertyName"]
// example: value.ri_idx; value.ri_startDate; value.ri_endDate;
});
Hope this helps!
In jQuery forEach working like this
$.each( obj, function( key, value ) {
alert( key + ": " + value );
});
If you are using Array for loop than key is array index and value values and if you are using javascript object then object key is key and value is object value for the particular key.
You can read more at jQuery documentation.
Just use property names in object. Check if this helps
$(document).ready(function() {
var responseData = [
{startdate: '2017-12-21', enddate: '2017-12-22', idx: '1'},
{startdate: '2017-11-21', enddate: '2017-11-22', idx: '1'},
{startdate: '2017-10-21', enddate: '2017-10-22', idx: '1'}
];
var html = '';
$.each(responseData, function(key, value) {
html += "<option value=" + value.startdate + ">" + value.startdate + "</option>";
});
$('#doctorSelect').html(html);
});
How can I define an array of arrays and pass that variable into a function so I can manipulate it at JavaScript?
As like:
JSP side:
object.method({ {"#id1",2}, {"#id2",3}...});
...
JS side:
var object= {
defaults: {
idSelector: "#id1"
},
method: function(options) {
if (options && !jQuery.isEmptyObject(options))
$.extend(this.defaults, options);
var that = this;
var opts = that.defaults;
//Try to reach every array step by step?
});
}
}
use json data format .
Convert your object into json string in your JSP page.
Parse that JSON string in your javascript.
Here's one of the ways to do that:
Your servlet can return a text, representing a json dictionary. Here's the documentation of a JSON API http://www.json.org/java/
Your javascript client code can fetch this json dictionary, something like:
$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
});
now items points to a bunch of <li> with your results
The functions' variable that will get the values should be like that(JSON format will be used):
defaults: [{
idSelector: '',
faqId: ''
}]