How to iterate a List of HashMap in jQuery [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've a requirement where in I receive a List of HashMap from a database query and I've to display that on the JSP.
The JSON object looks like below:
[
{"UNIT_NM":"ATLANTA", "UNIT_CD":"A00"},
{"UNIT_NM":"ATLANTA CKO","UNIT_CD":"A00"},
{"UNIT_NM":"DALLAS", "UNIT_CD":"D00"},
{"UNIT_NM":"DALLAS CKO", "UNIT_CD":"D00"}
]
I've to display it in dropdown like:
"<option value='A00'> A00 ATLANTA</option>";
"<option value='A00'> A00 ATLANTA CKO</option>";
"<option value='D00'> D00 DALLAS</option>";
"<option value='D00'> D00 DALLAS CKO</option>";
The JS code is:
$.ajax({
url:indexContextRoot+"populateManualCsoCodes",
type:"post",
async:true,
success: function(data){
var listItems= "<option value=''>Please Select</option>";
$.each(data, function(key, value) {
listItems+= "<option value='" + key + "'>" + value + "</option>";
});
$("#manualCsoCodes").html(listItems);
}
});
I'm getting the dropdown as:
[object][Object]
[object][Object]
[object][Object]
[object][Object]
Any suggestions please!

The each() callback function has two parameters: 1) The index of the array element, and 2) The array element. So key is going to be 0, 1, 2, etc. and value is going to be the js object at that index position. So you need to do:
$.each(data, function(key, obj) {
var str = obj["UNIT_CD"];
listItems+= "<option value='" + str + "'>" + str + " " + obj["UNIT_NM"] + "</option>";
});

To make this a bit more modular and involve lesser HTML, here's my take on this :
var data = [
{
"UNIT_NM": "ATLANTA",
"UNIT_CD": "A00"
},
{
"UNIT_NM": "ATLANTA CKO",
"UNIT_CD": "A00"
},
{
"UNIT_NM": "DALLAS",
"UNIT_CD": "D00"
},
{
"UNIT_NM": "DALLAS CKO",
"UNIT_CD": "D00"
}
];
//init first option
var $option = $("<option/>", {
"value": '',
"html": "Please Select"
});
//add that to an array
var options = [$option];
//iterate over data
$.each(data, function (key, value) {
// value now contains a row eg., when key = 0, value = { "UNIT_NM": "ATLANTA", "UNIT_CD": "A00" }
//clone the default option, change the value and the HTML, then push into options array
options.push($option.clone().val(value.UNIT_CD).html(value.UNIT_CD + " " + value.UNIT_NM));
});
//add that array into select
$("#manualCsoCodes").html(options);
The idea is to create an options array, which fills up with jQuery objects with tag name option and then place that in the select tag. Here's a demo
Oh, before i forget, each iterates row-wise. So, in any iteration of each, you'll get a row of data. For example,
if key === 2, then value === {
"UNIT_NM": "DALLAS",
"UNIT_CD": "D00"
}
So, to access UNIT_NM & UNIT_CD, you'll have to use value.UNIT_NM & value.UNIT_CD respectively. For more info on each, see docs.
Hope that helps!

listItems+= "<option value='" + value.UNIT_CD + "'>" + value.UNIT_CD + " " + value.UNIT_NM + "</option>";
PS: you could do that yourself if you used console.log(value);

Related

data showing in single option instead of multiple option from json array

I have a JSON array in a JSON file looks like this:
{
"states": [
{
"state": "Andhra Pradesh",
"districts": [
"Anantapur",
"Chittoor",
"East Godavari",
"Guntur",
"Krishna",
"Kurnool",
"Nellore",
"Prakasam",
"Srikakulam",
"Visakhapatnam",
"Vizianagaram",
"West Godavari",
"YSR Kadapa"]
}
]
}
and I am successfully able to load all states in the select element as a dependent select option
. when I select a state from a select element it populates a related array in the district select element.
but instead of the array showing a separate option it shows as one option:
Should I modify my JSON array in a different format?
jquery
$('#statePicker').on('change', function() {
$("#cityPicker").html('');
$.ajax({
url: "{{ asset('json/in-sc-list.json') }}",
type: "GET",
dataType: 'json',
success: function(res) {
$('#cityPicker').html('<option value="">Select City</option>');
$.each(res.states, function(key, value) {
if (value.state == $('#statePicker').val()) {
console.log(value.districts);
$("#cityPicker").append('<option value="' + value
.districts + '">' + value.districts + '</option>');
}
});
}
});
});
blade
<span>
<select id="statePicker" name="statePicker" required class="form-control"></select>
<select id="cityPicker" name="cityPicker" required class="form-control"></select>
</span>
Your data structure is fine. The issue is that you're not creating multiple option elements, you're only creating one. This part is off:
$("#cityPicker").append('<option value="' + value
.districts + '">' + value.districts + '</option>');
}
What you want to do is create an option element for each district, as follows:
for (const district of value.districts) {
$("#cityPicker").append('<option value="' + district + '">' + district + '</option>');
}
let statePicker = $('#statePicker').val();
let list = $("#cityPicker");
$.each(res.states, function(key, value) {
if (value.state == statePicker) {
$.each(items, function(item) {
list.append(new Option(item, item));
});
}
});
You need to loop value.districts because its an array, and also, you are doing it in a dirty way, you are initializing $("#cityPicker") on every loop, This might give some performance issues in future if the list items increases.

How to populate div tables and dropdownboxes with JSON and Javascript?

I've been trying to populate div tables with dummy JSON data but I cannot seem to do it. What I want to do is display certain data depending of the selection in a dropdownbox. Also I need to create new row with a new dropdownbox when an item is selected. Could you give me some advice of what's the best way to do it. I'm able to create something close to what I need in Angular but I need it in pure JavaScript. Thanks in advance!
structure of my div tables
Suppose in data you have json object
var data = [
{
"line": "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.",
"author": "Brian W. Kernighan",
"num" : ["1","2","3"]
},
{
"line": "Walking on water and developing software from a specification are easy if both are frozen.",
"author": "Edward V Berard",
"num" : ["5","0","15"]
},
{
"line": "It always takes longer than you expect, even when you take into account Hofstadter's Law.",
"author": "Hofstadter's Law",
"num" : ["15","222","301"]
}];
and you want to populate all authors in above json object to table and num into respective dropdown element of table-row. Then following populateHTML() function populate object to table and num into respective dropdown element of table-row as shown in below image .
function populateHTML(data) {
if (typeof(data) == 'object') {
document.write('<table>');
for (var i in data) {
document.write('<tr><td>'+data[i].author+'</td><td><select>');
for(var j in data[i].num){
document.write('<option>' +data[i].num[j]+ '</option>');
}
document.write('</select></td></tr>');
}
document.write('</tr></table>');
} else {
document.write(' => ' + data);
}
}
This can be achieved with the following code: You can also check an example here: http://skillcram.com/JS_DivTable.htm
<script type="text/javascript" >
function populateTable() {
var tableData = {
products : [
{"id": 100,"name":"Laptop", "qty":1,"status": ["Delivered","Damaged","Missing"]},
{"id": 200,"name":"Monitor", "qty":2,"status":["Refused","Partial"]}
]
}
var tableBody = document.getElementsByClassName("divTableBody");
for (i in tableData.products){
tableBody[0].innerHTML += "<div class=\"divTableRow\"> " +
"<div class=\"divTableRowCell\">"+ tableData.products[i].id +" </div> " +
"<div class=\"divTableRowCell\">"+ tableData.products[i].name +" </div> " +
"<div class=\"divTableRowCell\">"+ tableData.products[i].qty +" </div> "+
"<div class=\"divTableRowCell\">"+ getSelectHTMl(tableData.products[i].status) +
" </div> "+
"</div>";
}
}
function getSelectHTMl(status) {
selectHTMlStr = "<select> ";
for (j in status){
selectHTMlStr +=
"<option value=\""+ status[j]+ "\" id=\"itemStatus\" >"+status[j]+ " </option>" ;
}
selectHTMlStr += "</select>" ;
return selectHTMlStr;
}
</script>

Set selected of a dynamic populated selectbox value ajax

I have a select element that populates another select on change. Everything works fine, but I want to automatically set the value of the new select to the first item in the array.
$.get($(this).data('url'), {
option: $(this).val()
}, function(data) {
var subcat = $('#models');
var options = " ";
subcat.empty();
$.each(data, function(index, element) {
options += "<option value='" + element.id + "'>" + element.name + "</option>";
});
subcat.append(options);
});
What I want to do is to set the selected value of models to first item.
Your option variable is just a string, and you can't append a string like that to the subcat object and have it turn into <option>s automatically.
Instead try one of these methods inside your $.each() function:
subcat.append($("<option value='" + element.id + "'>" + element.name + "</option>"));
or:
subcat.append($("<option/>").val(element.id).text(element.name));
The first option should be selected by default.
Fiddle

Generate a list [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
So I want to generate a list from an Array I wrote the following code:
function list() {
table = new Array("Rabat", "Casablanca", "Marrakech", "Fes", "Tanger", "Agadir");
document.write('<select id="list1" size=6><option value="Rabat">Rabat</option><option value="Casablanca">Casablanca</option></select>');
}
It works but I'm wondering if there's a better coding
You can use a loop to go through all items in the list:
// you can use this instead of the new Array() syntax:
var table = ["Rabat", "Casablanca", "Marrakech", "Fes", "Tanger", "Agadir"];
var select = '<select id="list1" size="6">';
for (var i=0; i<table.length; i++) {
select += '<option value="' + table[i] + '">' + table[i] + '</option>';
}
select += '</select>';
document.write(select); //you should probably not use document.write though...
Usually it is better not to use document.write though. Instead, you should try selecting the element you want to append to, and then add the text to that.
HTML:
<select id="list1" size="6"></select>
JS:
function list() {
var i,
table = ["Rabat", "Casablanca", "Marrakech", "Fes", "Tanger", "Agadir"],
select = document.getElementById('list1'),
out;
for (i = 0; i < table.length; ++i) {
out += "<option value='" + table[i] + "'>" + table[i] + "</option>";
}
select.innerHTML = out;
}
FIDDLE:
http://jsfiddle.net/Z9XKp/
you can loop over the array and make your string rather than writing same code again and again .
var list="";
for(i=0;i<table.length;i++){
var val=table[i];
list+="<option value='"+val+"'>"+val+"</option";
}

Select List Generated using JSON and jQuery appends empty options

I have a field that represents a zip code of a user. When the user leaves that text box, an AJAX request is sent to the server to receive cities that may be associated with that zip code.
I am trying to use the JSON received from that request to populate a select list to replace the text box that is currently assumed for city (if one city is returned, I just change the value of the text box).
For example, a user puts in 20910 as their zip code and it returns Silver Spring. I replace the textbox for city with Silver Spring. Another user puts in 84107 as their zip code and it replaces the textbox with a select list of Murray, Salt Lake City.
It receives the JSON just fine, but I am not sure if I am doing something wrong in my JavaScript. When the select is rendered, it gives blank fields after each value.
Here is my jQuery:
$('#AddressData_ZipCode').blur(function() {
var zip = $('#AddressData_ZipCode').val();
var pattern = /^\d{5}([\-]\d{4})?$/;
if (zipCode.length > 0 && pattern.test(zip)) {
$.getJSON("/GeneralInfo/GetCitiesInZip", { zipCode: zip }, function(data) {
if (data.length > 1) {
var citiesComboBuilder = "<select id='AddressData_City'>";
for (var i = 0; i < data.length; i++) {
citiesComboBuilder += "<option value='" + data[i] + "'>" + data[i] + "<option/>";
}
citiesComboBuilder += "</select>";
$('#AddressData_City').replaceWith(citiesComboBuilder);
}
else
$('#AddressData_City').val(data);
});
}
});
This is the returned JSON:
["Murray","Salt Lake City"]
And this is the HTML that I receive after the function runs:
<select id="AddressData_City">
<option value="Murray">Murray</option>
<option/>
<option value="Salt Lake City">Salt Lake City</option>
<option/>
</select>
Any help would be great. Any suggestions to improve this code would be great also. Thanks.
Here is your problem:
citiesComboBuilder += "<option value='" + data[i] + "'>" + data[i] + "<option/>";
Here is your solution:
citiesComboBuilder += "<option value='" + data[i] + "'>" + data[i] + "</option>";
The option tag is closed wrong in your JavaScript, you have <option/>. It looks like the browser is trying to correct it and failing.

Categories

Resources