I am trying to generate an HTML select menu using a javascript array. The array keys should be used as values of options. And if the array keys are entered as numbers(as what I have done in my code) they should be accepted.
a([selected="No of rooms", 1="1", 2="2", 3="3", 4="4", 5="5"]);
function a(x) {
elementString = "<select>";
for(var i in x) {
elementString += '<option value="">'+i+'</option>';
}
elementString += "</select>";
alert(elementString);
}
But this code does not work. And I could not find a way to use array keys as the values
of options. Another question I got is, if I put numbers as keys it does not work(This is a requirement).
jsfiddle
Edit: jsfiddle link works now
Your code is syntactically wrong and JavaScript doesn't have associative arrays, the key of array's elements is their index, however you can use an object:
a({selected: "No of rooms", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5"});
But it should be noted that JavaScript object doesn't have order, ie, the generated elements may be different in each browser. If you want to keep the order you should use an array, in this case an array of objects:
a([{
text: "No of rooms",
value: "...",
selected: true
}, {
text: "one",
value: "1",
selected: false
}]);
function a(x) {
var elementString = "<select>";
for (var i = 0; i < x.length; i++) {
elementString += '<option value="' + x[i].value + '"' + (x[i].selected ? "selected='selected'" : '') + '>' + x[i].text + '</option>';
}
elementString += "</select>";
// document.body.innerHTML = (elementString);
}
If you have assoc massive like var arr={"room1" : "1", "room2" : "2"} then you can use keys of array like new array:
var keys = Object.keys(arr);
var k = keys.length;
var elementString = "<select>";
for(var i=0; i<k; i++) {
elementString += '<option value="'+keys[i]+'">'+arr[keys[i]]+'</option>';
}
elementString += "</select>";
And more simple method is:
var arr = {"room1" : "1", "room2" : 2};
for (var i in arr) {
elementString += '<option value="'+i+'">'+arr[i]+'</option>';
}
elementString += "</select>";
The syntax of your array is wrong.
check this fiddle
change your array as follows
var arr= ["No of rooms", "1", "2", "3", "4", "5"];
if you want to use key- value pairs, use an array of json objects.
more about json
update: fiddle using json
var arr = [{
value: '1',
data: "1"
}, {
value: '2',
data: "2"
}, {
value: '3',
data: "3"
}, {
value: '4',
data: "4"
}, {
value: '4',
data: "4"
}];
a(arr);
function a(x) {
elementString = "<select><option value='0' selected>" + "No of rooms</option>";
for (var i in x) {
elementString += '<option value="' + x[i].value + '">' + x[i].data + '</option>';
}
elementString += "</select>";
alert(elementString);
}
Related
I'm picking up a JSON object using a promise:
var x = get();
x.done(function(data) {
for(var i in data) {
}
});
which is returning this data when i do console.log(data);
[{…}]
0:
customer: "9028"
data:
active: "1"
customer: "9028"
description: ""
id: "13717"
inherited: "0"
name: "Out of Hours"
priority: "1"
shared: "0"
sound: ""
__proto__: Object
voip_seq: "4"
__proto__: Object
length: 1
__proto__: Array(0)
so that is working fine, but within my for loop, I want to add 2 items to data
I tried adding this into my .done
var obj = { name: "Light" };
data.push(obj);
But that didn't add to data
My for loop looks like this:
for(var i in data) {
var m = '<option value="' + data[i].data.id + '"'
if(data[i].data.id == selected_val) {
m += ' selected="selected"';
}
m += '>' + data[i].data.name + '</option>';
$('#' + value_element_id).append(m);
}
If you want to add two more items to your select, you simply need to push new objects into your data array before your loop starts. The objects must contain the structure and properties ("name" and "id" within a "data" sub-property) matching the JSON coming from the Promise, so that your loop code can process them.
In the simplest case, it could be as straightforward as
x.done(function(data) {
data.push({ "data": { "name": "light", "id": 1234 } });
data.push({ "data": { "name": "dark", "id": 5678 } });
for(var i in data) {
var m = '<option value="' + data[i].data.id + '"'
if (data[i].data.id == selected_val) {
m += ' selected="selected"';
}
m += '>' + data[i].data.name + '</option>';
$('#' + value_element_id).append(m);
}
});
Demo: https://jsfiddle.net/a286b7fw/1/
In this case I think data is not an array so it hasn't .push() method. You can add property to object like this:
for(var i in data) {
var m = '<option value="' + data[i].data.id + '"'
if(data[i].data.id == selected_val) {
m += ' selected="selected"';
}
m += '>' + data[i].data.name + '</option>';
$('#' + value_element_id).append(m);
// here it will add obj to data
var obj = {name: "Light"};
data = {
...data,
obj
}
}
Here is my code:
$.ajax({
type: "POST",
url: "localhost/api.php",
data: {id:user_id},
cache: false,
success: function(data) {
var obj = $.parseJSON(data);
if (obj.msg == "1")
{
$.each(obj.userList, function(i,value) {
var jArray = <?php echo json_encode($groupData ); ?>;
list = [];
for (var i = 0; i < jArray.length; i++) {
list.push('<option id=' + jArray[i].Group_Id + ' value=' + jArray[i].Group_Name + '>' + jArray[i].Group_Name + '</option>');
}
var html ="<tr>"+
"<td>"+value['id']+"</td>"+
"<td>"+value['groupID']+"</td>"+
"<td><select name='Group[]''>"+list+ "</select></td>";
$('table#List tbody').append(html);
});
}
},
alert('Error');
});
I'm dynamically constructing the html based on the ajax response.
In the code snippet >
var jArray = <?php echo json_encode($groupData ); ?>;
list = [];
for (var i = 0; i < jArray.length; i++) {
list.push('<option id=' + jArray[i].Group_Id + ' value=' + jArray[i].Group_Name + '>' + jArray[i].Group_Name + '</option>');
}
$groupData is a PHP array. So I'm converting it into a Javascript array and using this jArray to generate the "option" and push the resulting list array. I'm appending this list array into the html and this much is working perfectly. Now there are 6 groups and one of them is already set for a particular user in the database. So currently none of the "option" has selected attribute. I'm having trouble in comparing jArray[i].Group_Id with value['groupID']. What I want to achieve is I want to compare jArray[i].Group_Id with value['groupID'] and if they are equal then set a selected attribute to that particular . How do I write an if statement for the comparison inside the "option" ?
Here's some example code showing this working:
const jArray = [{Group_Id: 1, Group_Name: 'One'}, {Group_Id: 2, Group_Name: 'Two'}];
const userList = [{id: 'user1', groupID: 2}, {id: 'user2', groupID: 2}, {id: 'user3', groupID: 1}];
$.each(userList, function(x,value) {
list = [];
for (var i = 0; i < jArray.length; i++) {
list.push('<option id=' + jArray[i].Group_Id + ' value=' + jArray[i].Group_Name + (jArray[i].Group_Id == value.groupID ? ' selected ' : '') + '>' + jArray[i].Group_Name + '</option>');
}
var html ="<tr>"+
"<td>"+value.id+"</td>"+
"<td>"+value.groupID+"</td>"+
"<td><select name='Group[]''>"+list+ "</select></td>";
$('table#List tbody').append(html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="List">
<tbody></tbody>
</table>
The important piece missing from your code being:
(jArray[i].Group_Id == value.groupID ? ' selected ' : '')
Not sure how to even title this question but i tried my best to condense it.
I have a key / value array that i need to loop through and print out as options to a select field. My issue is that i need to match an ID with a value in the array and give that option a selected attribute.
** Cannot use ES6 syntax **
My array:
groups =
[
{ name:"eng1",
value: "12"
},
{ name: "eng2",
value: "247"
},
{ name: "eng23",
value: "112"
},
];
My loop:
var targetGroupId = 247;
for (i = 0; i < groups.length; i++) {
if (groups[i].Value = targetGroupId) {
html += "<option value'" + groups[i].Value + "' selected='selected'>" + groups[i].Name + "</option>";
} else {
html += "<option value='" + groups[i].Value + "'>" + groups[i].Name + "</option>";
}
}
I need to print out all three items in the array as options. However the item matching targetGroupId needs to have the selected attribute.
Any guidance is much appreciated!
You have three issues
Comparing values with = rather than === .
You're using capitalized keys.
Comparing string with numbers.
var groups = [{name: "eng1",value: "12"},{name: "eng2",value: "247"},{name: "eng23",value: "112"},],
html = '',
targetGroupId = 247;
for (var i = 0; i < groups.length; i++) {
if (/*Convert to number ->*/+groups[i].value === targetGroupId) {
html += "<option value'" + groups[i].value + "' selected='selected'>" + groups[i].name + "</option>";
} else {
html += "<option value='" + groups[i].value + "'>" + groups[i].name + "</option>";
}
}
console.log(html);
You have the following issues with your code:
You are using Value property instead of value. Replace Value with value everywhere in your code.
Second, you need to correct this statement
if (groups[i].Value = targetGroupId) {
to this:
if (groups[i].value == targetGroupId) {
I've used == to auto-coerce the values for the comparison because targetGroupId is a number whereas value in the object is a string.
The keys name is case sensitive.So Value & Name need to be match the case
Also the value is string but the targetGroupId is integer. So need to convert the string to number or vice versa.
Beside groups[i].Value = targetGroupId is not right , you need to do the quality check instead of assigning the value
var groups = [{
name: "eng1",
value: "12"
},
{
name: "eng2",
value: "247"
},
{
name: "eng23",
value: "112"
},
];
var html = '';
var targetGroupId = 247;
for (i = 0; i < groups.length; i++) {
if (+groups[i].value === targetGroupId) {
html += "<option value'" + groups[i].value + "' selected='selected'>" + groups[i].name + "</option>";
} else {
html += "<option value='" + groups[i].value + "'>" + groups[i].name + "</option>";
}
}
document.getElementById('test').innerHTML = html
<select id='test'></select>
Situation : I receive JSON array from jQuery <-> PHP Ajax request. Here's structure of unparsed JSON aray :
{"Focus":{"id":2,"brand":"Ford","name":"Focus"}}
And after using JSON.parse(json); the structure looks like :
Focus: Object
brand: "Ford"
id: 2
name: "Focus"
Problem : I want to access all array's '1st tier' elements and use them like an object, but none of the following ways works :
for (var entity in dataTable)
{
formattedText += entity['brand'] + " " + entity['name'] + "<br>";
OR
formattedText += entity.brand + " " + entity.name + "<br>";
OR
formattedText += dataTable[0]['brand'] + " " + dataTable[0]['name'] + "<br>";
}
Any solutions how to read values of all object in this array?
The for..in loop uses keys and does not return the elements themself: for (var key in dataTable)You would then access each element with dataTable[key]. The key is actually the name of the Element.
You where using it as you would use a for..of loop, but that is a new feature not supported in all Browsers yet.
Demo:
var dataTable = {"Focus":{"id":2,"brand":"Ford","name":"Focus"}}
var formattedText = ""
for (var key in dataTable)
{
formattedText += dataTable[key]['brand'] + " " + dataTable[key]['name'] + "<br>";
}
document.write(formattedText)
Object.keys will return array of all the keys of the object
You can loop(forEach/for-loop) through the keys to get the expected output.
Using forEach:
var dataTable = {
"Focus": {
"id": 2,
"brand": "Ford",
"name": "Focus"
}
}
var keys = Object.keys(dataTable);
var str = '';
keys.forEach(function(item) {
str += dataTable[item].brand + " " + dataTable[item].name;
});
alert(str);
Using for-loop:
var dataTable = {
"Focus": {
"id": 2,
"brand": "Ford",
"name": "Focus"
}
}
var keys = Object.keys(dataTable);
var str = '';
for (var i = 0, len = keys.length; i < len; i++) {
str += dataTable[keys[i]].brand + " " + dataTable[keys[i]].name;
}
alert(str);
The correct syntax to write this would be:
When you loop, you'll get the key name in the variable entity and then use that to get the value, also, you need to access the associative array inside the first key i.e. Focus
var dataTable = JSON.parse('{"Focus":{"id":2,"brand":"Ford","name":"Focus"}}');
var formattedText = '';
for (var entity in dataTable.Focus) {
formattedText += dataTable.Focus['brand'] + " " + dataTable.Focus['name'] + "<br>";
}
Sounds like you're using each function in a wrong way. in your each function change arguments to key and value like this:
$.each(dataTable, function (key, value) {
//access key and values here
});
In your case u should iterate again over key and values of your key values.
Am trying to populate drop down from a json as per below code and filter them.
I could achieve for direct fields but could't get the dropdown loaded for nested fields. Once the two drop down are populated, I would like to filter them to see the list of pid's for each combination.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
</head>
<body>
Location: <select id="Location" name="Location"></select>
Category: <select id="Category" name="Category"></select>
<button onclick="javascript:getcount()">Search</button>
<div id="result" style="color:#0094ff;font-size:20px;margin-top:100px;">
Number of Users found : <div id="res"></div>
</div>
<div id="detailedresult" style="color:#0094ff;font-size:20px;margin-top:100px;">
PID's : <div id="pidRes"></div>
</div>
<script type="text/javascript">
var jsonList = {
"Users": [{ "pid": "2", "loc": "Bangalore", "cat": [{ "dname": "Hotels" }, { "dname":"Travel" }, { "dname":"Banking" }] },
{ "pid": "3", "loc": "Chennai", "cat": [{ "dname":"Hotels" }, { "dname":"Travel" }, { "dname":"Banking" }] },
{ "pid": "4", "loc": "Delhi", "cat": [{ "dname":"Hotels" }, { "dname":"Travel" }, { "dname":"Healthcare" }] },
{ "pid": "5", "loc": "Hyderabad", "cat": [{ "dname":"Retail" }, { "dname":"Insurance" }, { "dname":"Banking" }] },
{ "pid": "6", "loc": "Hyderabad", "cat": [{ "dname":"Ecommerce"},{"dname":"Banking"},{"dname":"Healthcare"},{"dname":"Travel"},] }]
}
$(document).ready(function () {
var count = Object.keys(jsonList.Users).length
$('#res').html(count);
var listItems= "";
for (var i = 0; i < jsonList.Users.length; i++){
listItems+= "<option value='" + jsonList.Users[i].pid + "'>" + jsonList.Users[i].loc + "</option>";
}
$("#Location").html(listItems);
var listItems3 = "";
for (var i = 0; i < jsonList.Users['cat']['dname'].length; i++) {
listItems2 += "<option value='" + jsonList.Users[i].pid + "'>" + jsonList.Users[i].cat.dname + "</option>";
}
$("#Category").html(listItems3);
}
);
function getcount()
{
var loc = document.getElementById('Location').value;
var cat = document.getElementById('Category').value;
var count = Object.keys(jsonList.Users).length // Where condition required.. when Location and Category are available.. For each combination (Location + Category), how many users and what are the pid's
$('#res').html(count);
}
</script>
What am I missing in above code for Category drop down generation ?
How can I filter the json based on location and category values (List of respective pid's for each combination) ?
EDIT:
Requirement:
First: List of pid's who are from Location 'Bangalore' AND has category 'Banking' (Resultant pid = 2)
Second: List of pid's who are either from Chennai OR has category Ecommerce category (Resultant pid => 3,6)
Not sure what you want, but here is a working set of dropdowns that populate based on the json provided. You may have been looking for this loop to populate the categories
for (var i = 0; i < jsonList.Users.length; i++){
listItems+= "<option value='" + jsonList.Users[i].pid + "' data-ind='"+i+"'>" + jsonList.Users[i].loc + "</option>";
pidres+= "Location: " +jsonList.Users[i].loc+ ". PID: " +jsonList.Users[i].pid+ ". Number of categories: " +jsonList.Users[i].cat.length + "<br />"
//loop all cats
for (var j = 0; j < jsonList.Users[i].cat.length; j++) {
listItems3 += "<option value='" + jsonList.Users[i].cat[j].dname + "'>" + jsonList.Users[i].cat[j].dname + "</option>";
}
}
//then to filter the results
$("#Category > option").each(function () {
if(usedNames[this.text]) {
$(this).remove();
} else {
usedNames[this.text] = this.value;
}
});
Here is a demo