here in this code i am trying to get the json value. i am able to get the key value, but i am not able to get the val's value.
How can i do this?
Jquery code:
$.getJSON('data.json', function(data) {
var items = [];
$.each(data, function(key, val) {
alert(key);
alert(val);
items.push('<option value="' + key + '">'+key+'</option>');
//items.push('<li id="' + key + '">' +key + '</li>');
});
$('#project-list').html(items.join(''));
});
here is json data
{
"trng-java": {"1":"5"},
"trng-jast": {"2":"5"},
"trng-caml": {"3":"4"},
"trng-linx": {"1":"5"}
}
When i run this, i am getting the key value, but val's value is coming as Object object.
the value is an array it seems, like others suggested use val[index] to get the values but if you want it to be a string use
var valString = val.toString();
this will return 1,5 , 2,5 ...
Try accessing: val[0]
$.getJSON('data.json', function(data) {
var items = [];
$.each(data, function(key, val) {
alert(key);
alert(val[0]);
items.push('<option value="' + key + '">'+key+'</option>');
//items.push('<li id="' + key + '">' +key + '</li>');
});
$('#project-list').html(items.join(''));
});
Related
I am trying to serialize value of form elements, where my combox is dynamicall added after user click.
I'm getting value from static combobox bt nt from dynamic combobox.
my code:
<script>
//submit data
$(function (a) {
$("form").submit(function (event) {
console.log($(this).serializeArray());
event.preventDefault();
});
});
// populate entree item to select menu
function populate() {
// only declare the variables once
var json = <?php echo $json; ?>, obj, option = ' ', i;
for (var i = 0; i < json.length; i++) {
obj = json[i];
option += '<option value="' + obj.id + '">' + $.trim(obj.title) + '</option>';
}
return option;
}
//add more select box when addmore click
$(function (b) {
var i = 0;
$("a#addmore").click(function () {
i++;
$("p#entree").append('<select name="entree' + i + '">' + populate() + '<select><br>');
});
});
</script>
i got the value when i put my form outside the table. I dnt know why table is blocking the process to get value.
I use jquery in comboboxes, and I'm not abele to get the comboboxes in the interface to be displayed. The error in firebug is the following :
TypeError: $ is undefined : $.widget("ui.combobox", {
I'm using the following file jquery.ui.combobox.js:
Code :
$.widget("ui.combobox", {
options: {
openDialogButtonText: "+",
dialogHeaderText: "Add option",
saveButtonImgUrl: null,
closeButtontext: "Ok"
},
_create: function() {
var selectBox = $(this.element),
id = selectBox.attr("id"),
self = this;
selectBox.addClass("ui-combobox");
// create HTML to inject in the DOM
this.addHtml(id, selectBox);
// turn dialog html into a JQuery UI dialog component
this.addDialog(id);
// #todo set proper button height (roughly equal to select height)
$("#" + id + "-button-opendialog").bind("click", function() {
$("#" + id + "-editor-dialog").dialog("open");
}).button();
$("#" + id + "-button-save").bind("click", function() {
self.addOption(id, selectBox);
}).button();
this._init();
return this;
},
addHtml: function(id, selectBox) {
var imgHtml = "";
if (this.options.saveButtonImgUrl != null) {
imgHtml = '<img src="' + this.options.saveButtonImgUrl + '" alt="opslaan" />';
}
$(' <button id="' + id + '-button-opendialog">' +
this.options.openDialogButtonText +
'</button>' +
'<div id="' + id + '-editor-dialog" class="ui-combobox-editor">' +
'<input id="' + id + '-newitem" type="text" /> ' +
' <button id="' + id + '-button-save">' +
imgHtml + ' Opslaan' +
' </button>' +
'</div>').insertAfter(selectBox);
},
addDialog: function(id) {
var options = this.options;
$("#" + id + "-editor-dialog").dialog( {
autoOpen: false,
modal: true,
overlay: {
opacity:0.5,
background:"black"
},
buttons: {
// #todo make button text configurable
"Ok": function() {
$("#" + id + "-editor-dialog").dialog("close");
return;
}
},
title: options.dialogHeaderText,
hide: 'fold'
});
},
addOption: function(id, selectBox) {
var newItem = $("#" + id + "-newitem");
// #todo do not allow duplicates
if (newItem !== null && $(newItem).val().length > 0) {
// #todo iterate over options and get the highest int value
//var newValue = selectBox.children("option").length + 1;
var highestInt = 0;
selectBox.children("option").each(function(i, n) {
var cInt = parseInt($(n).val());
if (cInt > highestInt) {
highestInt = cInt;
}
});
var newValue = highestInt + 1;
var newLabel = $(newItem).val();
selectBox.prepend("<option value='" + newValue + "' selected='selected'>" + newLabel + "</option>");
this._trigger("addoption", {}, newValue);
// cleanup and close dialog
$(newItem).val("");
$("#" + id + "-editor-dialog").dialog("close");
} else {
this._trigger("addoptionerror", {}, "You are required to supply a text");
}
},
_init: function() {
// called each time .statusbar(etc.) is called
},
destroy: function() {
$.Widget.prototype.destroy.apply(this, arguments); // default destroy
// $(".ui-combobox-button").remove();
// $(".ui-combobox-editor").remove();
}
});
Can you please help me?
The message "$ is undefined" means that the function called "$" is not defined anywhere on your page. Thus, when this code is executed, it does not know what to do when this line is encountered.
The $ function is defined by jQuery. Therefore, the message is indicating that it hasn't loaded the jQuery library by the time your code is executed. This could be for a number of things
You haven't included the full jQuery library on your page. This may be because you have forgotten to include it or you have only included some extension to jQuery such as jQuery.UI.
If you are unsure, try adding the following line to the top of your head element in your HTML. Make sure you haven't put any JS before this line:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
You have included jQuery but it is failing to load. This may be because the link you are using is incorrect. Double check by using the Net Panel in Firebug.
jQuery is included on your page, but you have included your own JS first. This won't work because the $ function won't get defined until jQuery is loaded, but your code will try and execute first. Check the order in which you are including your JS and make sure that jQuery is first.
I have a JSON file that is being used to autopopulate some select boxes. Every now and then (I can't recreate the fault, it appears to be random) the items in the drop down do not display until I refresh the page.
I've checked the console and log etc, the file is loading fine, no errors are appearing and I'm a little at a loss.
Any ideas?
Example of JSON and the script that reads it below.
Thanks.
"radAbsorbed" : [
{
"value" : "rad",
"name" : "Rad(rd)"
},
{
"value" : "millirad",
"name" : "Millirad(mrd)"
}]
and the script:
<script>
// JSON:
// The key is the class identifier, temp, area etc etc
// Value is being used for both ID and Value when the list is being populated
$.getJSON('JSON/conversionJSON.json', function(data){
console.log(data);
//for testing output only
var list = $("<ul />");
$.each(data, function (key, conversions) {
console.log(key + ":" + conversions);
$.each(conversions, function (index, conversion) {
console.log("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>");
if(key == "<?php echo $conversionType ?>"){
$("#from").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>');
//testing output
var elem = $("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>").appendTo(list);
}
});
});
//$("#testJSON").html(list);
});
</script>
EDIT:
Updated script.
$(document).ready(function(){
$.getJSON('JSON/conversionJSON.json', function(data){
console.log(data);
//for testing output only
var list = $("<ul />");
$.each(data, function (key, conversions) {
console.log(key + ":" + conversions);
$.each(conversions, function (index, conversion) {
console.log("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>");
if(key == "<?php echo $conversionType ?>"){
$("#from").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>');
$("#to").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>');
//testing output
var elem = $("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>").appendTo(list);
}
});
});
//$("#testJSON").html(list);
});
});
EDIT: Thanks everyone for their help, it seems to be working fine and looked like an amateur mistake on my part.
I think the problem is that your script is sometimes running before the document is ready.
Try wrapping your code in a document ready function:
$(function() {
$.getJSON(...)
// ...
});
This will make it so that the code doesn't execute before the elements it's affecting are created. For instance, if your code executes before the element with the ID from gets created, then $('#from') will not match any elements, and it won't work.
Wrapping it in a document ready function will make sure that your code waits until the elements have been created before executing.
Alternatively, you could move your <script> tag out of the head and place it right after the #from element in your HTML. This might help it load slightly faster.
I'm having the below output from an ajax script:
{"DATA":[{"COUNTRYCODE":"1","DESCRIPTION":"USA","COUNTRYID":"211"}, {"COUNTRYCODE":"1","DESCRIPTION":"Canada","COUNTRYID":"37"},{"COUNTRYCODE":"1","DESCRIPTION":"Dominican Republic","COUNTRYID":"224"},
I am trying to populate a select menu with info from this JSON data:
<script type="text/javascript" charset="UTF-8">
$.getJSON(
'getcountries.php',
function(data) {
var items = [];
$('#country').append(data);
$.each(data['DATA'], function(key, val) {
$.each(val, function(key, value) {
console.log(value);
});
});
}
);
Issue with it is that the $('#country').append(data) (or append(data['DATA']) always returns error "Value does not implement interface Node."
Could anyone point out how I could get the specific JSON data I have into the select script?
.append() only accepts HTML string, DOM Element, or jQuery Object
See: http://api.jquery.com/append/
I assume this is the result you actually want.
var data = {"DATA":[{"COUNTRYCODE":"1","DESCRIPTION":"USA","COUNTRYID":"211"},{"COUNTRYCODE":"1","DESCRIPTION":"Canada","COUNTRYID":"37"},{"COUNTRYCODE":"1","DESCRIPTION":"Dominican Republic","COUNTRYID":"224"}]};
var $select = $('#country').empty();
$select.append(
data.DATA.map(function (el, i) {
return $('<option>')
.val(el.COUNTRYID)
.text(el.DESCRIPTION)
.data('DATA', el); // in case you also want to access its COUNTRYCODE
})
);
jsFiddle: http://jsfiddle.net/terryyounghk/ZshG4/
DEMO: http://jsfiddle.net/q5Q3d/
var a = {
"DATA":[
{"COUNTRYCODE":"1","DESCRIPTION":"USA","COUNTRYID":"211"},
{"COUNTRYCODE":"1","DESCRIPTION":"Canada","COUNTRYID":"37"},
{"COUNTRYCODE":"1","DESCRIPTION":"Dominican Republic","COUNTRYID":"224"}
]
}
$.each(a.DATA, function(idx, val){
var option = "<option value='" + val.COUNTRYID + "'>" + val.DESCRIPTION + "</option>";
$('select').append(option);
});
Here is my funciton:
function getEmployeeList() {
alert("hello world3!");
$.getJSON(serviceURL + 'getemployees.php', function(data) {
alert("hello world4!");
$('#employeeList li').remove();
employees = data.items;
$.each(employees, function(index, employee) {
$('#employeeList').append('<li><a href="employeedetails.html?id=' + employee.id + '">' +
'<img src="pics/' + employee.picture + '"/>' +
'<h4>' + employee.firstName + ' ' + employee.lastName + '</h4>' +
'<p>' + employee.title + '</p>' +
'<span class="ui-li-count">' + employee.reportCount + '</span></a></li>');
});
$('#employeeList').listview('refresh');
});
}
When the page is ready, it will run this function, however, nothing is appended.
I have tested, all php can return correct format. What wrongs?? Please please help me...
You need to add the external host (in my case was mysite.localhost) in PhoneGap.plist under the "ExternalHosts" key.
I presume serviceURL is not on the same domain.
In that case you add callback=? in the end, and jQuery does some magic:
$.getJSON(serviceURL + 'getemployees.php?callback=?', function(data) {
...
If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.
jQuery API