Hello I have a following html
<select id="fld_base_profile_id" defaultValue="-1" class="m-wrap span10" field="fld_base_profile_id" appEditor="true"></select>
I have this in my ajax
$result['analyze_type'][] = array ("id" => $row[idatabase::FIELD_ID], "name" => $row[idatabase::FIELD_PROFILE_NAME]);
echo json_encode($result);
and in js part (by the way i'm using Prototype.js) :
var JSON = transport.responseText.evalJSON();
In console, my JSON.analyze_type looks like this
Array[1]
0: Object
id: "939"
name: "Reaktif İndüktif Kontrolü Ana Profili"
The question is, how can i parse this JSON data so it can change my html like
<option value="id">name</option> ??
EDIT: Solution:
this.baseProfile = $("fld_base_profile_id");
var JSON = transport.responseText.evalJSON();
this.type = JSON.analyze_type;
for(var i = 0; i < JSON.analyze_type.length; i++) {
var profile = JSON.analyze_type[i];
var opt = document.createElement("option");
opt.value = profile.id;
opt.text = profile.name;
this.baseProfile.appendChild(opt);
}
Try this
var el = document.getElementById('fld_base_profile_id');
for(var i = 0; i < JSON.length; i++) {
var profile = JSON[i],
opt = document.createElement("option");
opt.id = profile.id;
opt.value = profile.name;
el.appendChild(opt);
}
You could do it in a much cleaner way
Firstly make sure you are passing the Content-Type: application/json header in your JSON response - All of the Ajax methods in Prototype will automatically process the response as JSON and put it into transport.responseJSON
Then your javascript can clean up to this
this.baseProfile = $("fld_base_profile_id");
var type = transport.responseJSON.analyze_type;
type.each(function(item){
var option = new Element('option',{'value':item.id}).update(item.name);
this.baseProfile.insert(option);
},this);
You can use JSON.Parse to turn the JSON you get into an object. then you can loop over the items, assign each one to an <option> object and then append them to the select.
JavaScript - populate drop down list with array explains how to create the option tags.
Related
This is the code i am using to get the array and then add them to the select object.
var select = document.getElementById('select');
var theArray = localStorage.getItem("array")
JSON.parse(theArray)
if (theArray != null){
for (var i=0; i > theArray.length; i++){
select.add(theArray[i])
}
}
Here is the code i am using to set the localStorage values.
var select = document.getElementById('select');
var option = document.createElement("option");
option.text = visText;
option.value = actVal;
select.add(option)
theArray[theArray.length+1] = option;
localStorage.setItem("array",JSON.stringify(theArray))
Can anybody tell me how to fix this?
Looks like you forgot to assign the parsed Json to a variable:
let select = document.getElementById('select')
let data = JSON.parse(localStorage.getItem('array'))
for(let entry of data) {
select.add(new Option(entry))
}
Not 100% sure if it works but should do.
You can just call the session and local storage with dot notation. The snippet below shows this. However, the snippets here are sandboxed, and cannot be written to. So, to demonstrate how to populate a select element from an array, I used a try..catch block so when it errored out, it would at least populate the select options with the original array variable.
const array = new Array(10).fill(0).map((elm, idx) => (elm = idx, elm));
let arrayFromStorage;
try {
window.localStorage.myArray = JSON.stringify(array);
arrayFromStorage = JSON.parse(window.localStorage.myArray);
} catch (error) {
console.warn(error.message)
arrayFromStorage = array;
}
arrayFromStorage.forEach(elm => {
const opt = document.createElement('option');
opt.value = elm;
opt.innerText = `option ${elm}`;
document.querySelector('select').append(opt);
})
<select></select>
If you copy/paste this into a browser console, you can see that it can be set and called using dot notation
const array = new Array(10).fill(0).map((elm, idx) => (elm = idx, elm));
let arrayFromStorage;
window.localStorage.myArray = JSON.stringify(array);
arrayFromStorage = JSON.parse(window.localStorage.myArray);
I'm getting Response string same as like this.
var txtResponse = "{"Tom":{"Given Name":"Tom","Employee Number":"21"},"Sam":{"Given Name":"Sam","Employee Number":"23"},"Jack":{"Given Name":"Jack","Employee Number":"19"}}";
Need to put this on html drop down and assign Text as 'Given Name' and value as 'Employee Number' of each employee by java script.
I have used this to assign values to drop down for other array.
var select = document.getElementById("selectelement");
var optionContent = document.createElement("option");
optionContent.textContent = "";
optionContent.value = "";
select.appendChild(optionContent);
can you please help me to assign 'textContent' and 'value' from above response through loop.
You can iterate through all the keys in the json object like the following,
var txtResponse = '{"Tom":{"Given Name":"Tom","Employee Number":"21"},"Sam":{"Given Name":"Sam","Employee Number":"23"},"Jack":{"Given Name":"Jack","Employee Number":"19"}}';
var jsonResponse = JSON.parse(txtResponse);
var select = document.getElementById("selectelement");
Object.keys(jsonResponse).forEach(key => {
var optionContent = document.createElement("option");
optionContent.textContent = jsonResponse[key]['Given Name'];
optionContent.value = jsonResponse[key]['Employee Number'];
select.appendChild(optionContent);
})
let res:any='{"Tom":{"Given Name":"Tom","Employee Number":"21"},"Sam":{"Given Name":"Sam","Employee Number":"23"},"Jack":{"Given Name":"Jack","Employee Number":"19"}}';
this.res=JSON.parse(this.res);
console.log('res==',this.res)
let select=document.getElementById("selectelement");
for(let el in this.res){
let optionContent=document.createElement("option");
optionContent.innerHTML=this.res[el]['Given Name'];
optionContent.value=this.res[el]['Employee Number'];
select.appendChild(optionContent);
}
<select id="selectelement"> </select>
I am new to JSON and struggling with the following.
I have an external JSON file
teamSkills = '[\
{"name":"John", "team":"Red"}, \
{"name":"Anna", "team":"Green"}, \
{"name":"Peter", "team":"Orange"}\
]
I want my HTML file to read the team names and populate a drop down list. From searching the web and 'playing' with the code, I now have the following JavaScript however it uses an array not the external JSON (which will contain a lot of records):
var TeamName = ["Red", "Green", "Orange"];
var sel = document.getElementById('teamList');
var fragment = document.createDocumentFragment();
TeamName.forEach(function(team, index) {
var opt = document.createElement('option');
opt.innerHTML = team;
opt.value = team;
fragment.appendChild(opt);
});
sel.appendChild(fragment);
The HTML code:
<select id="teamList"></select>
Can this be updated to get the data from the external JSON file?
An array of objects and an array of strings are almost the same thing. You can replace TeamName with teamSkills then access the team from the inner object:
// Not sure what is the initial format of your data here,
// use JSON.parse('your string') if you have a string to start with
var teamSkills = [
{"name":"John", "team":"Red"},
{"name":"Anna", "team":"Green"},
{"name":"Peter", "team":"Orange"}
];
var sel = document.getElementById('teamList');
var fragment = document.createDocumentFragment();
// Here, iterate through the skills instead
teamSkills.forEach(function(skill, index) {
var opt = document.createElement('option');
// Here, access the team from the current skill object
opt.innerHTML = skill.team;
opt.value = skill.team;
fragment.appendChild(opt);
});
sel.appendChild(fragment);
you can use this code it will be working good with you
$.each(TeamName, function(key, value) {
$('#teamList').append($("<option></option>").attr("value",key).text(value));
});
Sorry for using different code :
let dropdown = $('#teamList');
const teamSkills = 'https://api.myjson.com/bins/1abhwz';
// Populate dropdown with list of provinces
$.getJSON(teamSkills, function(data) {
$.each(data, function(key, entry) {
dropdown.append($('<option></option>').attr('value', entry.name).text(entry.team));
})
});
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<select id="teamList"></select>
I'm looking to submit a form via an XHR but I'm having trouble getting a hold of the selected data to pass along.
<form>
<select multiple id="select" >
<option class="userOptions" value="1">Tyler Durden</option>
<option class="userOptions" value="2">Robert Paulson</option>
<option class="userOptions" value="3">Marla Singer</option>
</select>
</form>
What would be the best way to grab hold of the user selected values and pass them off to a page via an XHR?
I've tried things like document.getElementsByClassName("userOptions").selected but it's not returning anything. Also, should I pack this up as an array? Or is there a better way to send it? Thanks for your time!
Here is a function in vanilla Javascript that will help you:
function getMultiValue(selectId)
{
var list = document.getElementById(selectId),
selected = [],
i;
for (i = 0; i < list.options.length; i++) {
if (list.options[i].selected) {
selected.push(list.options[i].value);
}
}
return selected;
}
In the case of your example, you must use this way:
var values = getMultiValue('select');
If you want those values converted to a query string:
var queryString = 'select=' + values.implode('&select=');
If the values contain special characters, you must do this before the construction of the query string:
var i;
for (i = 0; i < values.length; i++) {
values[i] = escape(values[i]);
}
Or just change a little the previous function:
function getMultiValue(selectId, mustEscape)
{
var list = document.getElementById(selectId),
selected = [],
i;
for (i = 0; i < list.options.length; i++) {
if (list.options[i].selected) {
selected.push(mustEscape ? escape(list.options[i].value) : list.options[i].value);
}
}
return selected;
}
And use it this way:
var values = getMultiValue('select', true),
queryString = 'select=' + values.implode('&select=');
Use jQuery and its just simple!
You can do it like this: http://jsfiddle.net/Hm2KL/
$("#sendbtn").click(function() {
var data = $("#selectme").val();
alert(data);
$.ajax({
url: ..,
data: {data}
etc..
});
});
jQuery Ajax Doc: http://api.jquery.com/jQuery.ajax/
I keep having issues iterating over some JSON to put in select options
(btw, ignore the actual values for "label", those are garbage atm).
Here is an example that my php is passing into this:
[{"value":"1","label":"04-22-12"},{"value":"4","label":"04\/04\/12"}]
I am currently trying this loop:
*note, dateSelect is defined somewhere else
for (res in JSON.parse(request.responseText)) {
var date = document.createElement("option");
date.value = res.value;
date.text = res.label;
dateSelect.add(date, null);
}
However, it is adding "undefined" into my options...
How do I get it so each value and corresponding label is put in there correctly?
You have an Array, so don't for-in.
In your code, res is the property name (the index of the Array in this case) in the form of a string, so the properties you're looking for aren't going to be defined on the string.
Do it like this...
for (var i = 0, parsed = JSON.parse(request.responseText); i < parsed.length; i++) {
var res = parsed[i];
var date = document.createElement("option");
date.value = res.value;
date.text = res.label;
dateSelect.add(date, null);
}