I'm pulling data from a database into a json array.
I have this data
[{"id":"0","name":"red","percentage":"60"},{"id":"1","name":"blue","percentage":"58"},{"id":"4","name":"green","percentage":"12"}]
The div has a structure like below (simplified here), and I'd like to build rows with the data from the json array (javascript or jquery solution)
<div id="json"
<div class="row">
<div class="col-xs-5"><span id="name"></span></div>
<div class="col-xs-2"></div>
<div class="col-xs-5"><input type="number" id="percentage"></div>
</div>
</div>
Use append() and each()
var data =[{"id":"0","name":"red","percentage":"60"},{"id":"1","name":"blue","percentage":"58"},{"id":"4","name":"green","percentage":"12"}]
$.each(data,function(i,v) {
$('#json').append('<div class="row"> <div class="col-xs-5"><span class="name">'+v.name+'</span></div><div class="col-xs-2"></div><div class="col-xs-5"><input type="number" class="percentage">'+v.percentage+'</div></div>')
});
see demo
or pure javascript:
var data =[{"id":"0","name":"red","percentage":"60"},{"id":"1","name":"blue","percentage":"58"},{"id":"4","name":"green","percentage":"12"}];
var string ="";
for (i in data) {
string +='<div class="row"> <div class="col-xs-5"><span class="name">'+data[i].name+'</span></div><div class="col-xs-2"></div><div class="col-xs-5"><input type="number" class="percentage">'+data[i].percentage+'</div></div>';
};
document.getElementById('json').innerHTML =string
see demo
You can use the .hmtl() function of JQuery.
Just need to pass the html code to a dom element.
For example:
${"#json"}.html(" <div class="row">
<div class="col-xs-5"><span id="name"></span></div> </div>");
var data= [{"id":"0","name":"red","percentage":"60"},{"id":"1","name":"blue","percentage":"58"},{"id":"4","name":"green","percentage":"12"}]
data = $.parseJSON(data);
$.each(data, function(i, item) {
$("body").append('<div class="row">
<div class="col-xs-5"><span id="name">'+item.name+'</span></div>
<div class="col-xs-2"></div>
<div class="col-xs-5"><input type="number" id="percentage" value='+item.percentage+'></div>
</div>')
})
try this
try the each loop like this:
var data = [{"id":"0","name":"red","percentage":"60"},{"id":"1","name":"blue","percentage":"58"},{"id":"4","name":"green","percentage":"12"}];
$.each(data, function(i, o){
$('#json').append($('<div/>').addClass('row')
.append(
$('<div/>').addClass('col-xs-5')
.append($('<span/>').attr('id', 'name').text(o.name)))
.append(
$('<div/>').addClass('col-xs-2'))
.append(
$('<div/>').addClass('col-xs-5')
.append($('<input/>')
.attr('type', 'number')
.attr('id', 'percentage').val(o.percentage))
));
});
but beware: the id attribute have to be unique (i think you have to use the "name" attribute in your input element)
Refer demo here.
Please find code below:
HTML:
<div id="json"></div>
JS:
var data = [{
"id": "0",
"name": "red",
"percentage": "60"
}, {
"id": "1",
"name": "blue",
"percentage": "58"
}, {
"id": "4",
"name": "green",
"percentage": "12"
}];
$(function() {
$.each(data, function(key, value) {
$('#json').append('<div class="row"><div class="col-xs-5"><span id="name">' + value.name + '</span></div><div class="col-xs-2"></div><div class="col-xs-5"><input type="number" class="input form-control" id="percentage" value="' + value.percentage + '" /></div></div>')
});
});
CSS:
.input {
width: inherit;
}
Related
I have a complex object as shown below:
$scope.document =
{
"GENERAL_FIELDS": {
"Source_Type": "custom",
"Annotations": [
"216/content/Factiva_CM_001/Proteins",
"216/content/Factiva_CM_001/Fact"
],
"Content": [
" Baculovirus; Budded virus; Ultrastructure; Cryo-EM;"
],
"Title": [
"Budded baculovirus particle structure revisited"
]
},
"stn": {
"Document_Type": [
"Journal",
"Article"
]
}
}
I want to display all the fields present in "GENERAL_FIELDS" and "stn". Fields' value can either be string or array of strings. If it is array, I further want to ng-repeat on it and display the content. Following is my html:
<div id="titsec" class="comdocdet" ng-repeat="(category, group) in document">
<div ng-repeat="(key, value) in group">
<div class="pTitle">
{{key}}
</div>
<div class="contdesc">
<div ng-if="Array.isArray(value)">
<div ng-repeat="v in value">
{{v}}
</div>
</div>
<div ng-if="!Array.isArray(value)">
{{value}}
</div>
</div>
</div>
</div>
But ng-if="Array.isArray(value)" is never true and array fields are being displayed in object form: ["Journal","Article"]. What am I missing ?
Or add this in your controller and leave rest like it is.
$scope.isArray = angular.isArray;
html would be like this :
<div ng-if="isArray(value)">
<div ng-repeat="v in value">
{{v}}
</div>
</div>
<div ng-if="!isArray(value)">
{{value}}
</div>
Instead of accessing a method on the Array object directly in the template, you should do in your controller. So for example:
<div ng-if="vm.isValueAnArray(value)">
// Some html
</div>
Your controller:
function isValueAnArray(val) {
return Array.isArray(val);
}
I haven't tested it, but logic should be in the controller, not in the template.
This is an issue of Scoping
The scope of the template is relative to $scope in the controller, so when it looks for Array, it will look for that in the controller scope (e.g. $scope.Array).
One option is to use ng-if="window.Array.isArray(value)". See the working example below.
Another option is to set $scope.Array = Array.prototype in the controller. That way there is no need to reference window before calling Array.isArray().
Another option is to create an alias for Array.isArray() in the controller scope:
$scope.isValueAnArray = Array.isArray;
Then call that function to determine if the value is an array.
angular.module('ang', [])
.controller('cont', function($scope) {
//use this to avoid referencing window in the template
//$scope.Array = Array.prototype;
$scope.document = {
"GENERAL_FIELDS": {
"Source_Type": "custom",
"Annotations": [
"216/content/Factiva_CM_001/Proteins",
"216/content/Factiva_CM_001/Fact"
],
"Content": [
" Baculovirus; Budded virus; Ultrastructure; Cryo-EM;"
],
"Title": [
"Budded baculovirus particle structure revisited"
]
},
"stn": {
"Document_Type": [
"Journal",
"Article"
]
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ang" ng-controller="cont">
<div id="titsec" class="comdocdet" ng-repeat="(category, group) in document">
<div ng-repeat="(key, value) in group">
<div class="pTitle">
{{key}}
</div>
<div class="contdesc">
<div ng-if="window.Array.isArray(value)">
<div ng-repeat="v in value">
{{v}}
</div>
</div>
<div ng-if="!window.Array.isArray(value)">
{{value}}
</div>
</div>
</div>
</div>
</div>
here is my codepen link
my html code
<div id="main">
<h1>Wikipedia Viewer</h1>
<form class="form-inline">
<div class="container">
<div class="row">
<div class="col-sm-6 col-sm-offset-4 col-lg-7 col-lg-offset-4">
<div class="form-group">
<label class="sr-only" for="search">search</label>
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="button" class="btn btn-primary"><i class="fa fa-search"></i></button></form>
</div>
</div>
</div>
Surprise me!
</div>
<div id="search">
</search>
jquery code for making wikipedia api search call and then displaying title and overview.i want to associate links to respective article on dynamically created p element
$(document).ready(function() {
$("button").click(function() {
var article = $("input").val();
$.ajax({ //wikipedia api call
url: "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + article + "&format=json",
dataType: "jsonp",
success: function(data) {
for (var i = 0; i < data.query.search.length; i++) { //displaying titles and snippets accroding to search query. i want to associate link to each dynamically created p element.
var title = data.query.search[i].title;
var snippet = data.query.search[i].snippet;
$("#search").append("<p>" + title + "<br>" + snippet + "</p>");
}
$("#main").attr({
'style': 'display: none'
});
},
error: function() {
$("h1").html("oops");
}
});
});
});
Change your $("#search").append() as follows:
$("#search")
.append("<p><a href='https://en.wikipedia.org/wiki/" + title + "'>" + title + "</a>" +
"<br>" + snippet + "</p>"
);
Codepen
I'm trying to display data from a certain part of a string of JSON data.
Below is the part i want to display.
{
"-rank": "3",
"-teamId": "t3",
"-name": "Arsenal",
"-played": "31",
"-won": "17",
"-drawn": "7",
"-lost": "7",
"-for": "52",
"-against": "30",
"-points": "58",
"-goalDifference": "22"
Below is the JS.
$scope.leagueTable = $scope.myData.LeagueTable.Table.TeamPosition;
//League Table
for( var i = 0; i < $scope.leagueTable.length; i++) {
if($scope.leagueTable[i]['-teamId'] == "t3") {
$scope.arsenalStats = $scope.leagueTable[i];
break;
}
}
console.log($scope.arsenalStats);
And below is the HTML I am using. I just get blank results. no errors.
<div class="row" ng-repeat="val in leagueTable| limitTo:-1">
<div class="col">{{arsenalStats[$index]['-played']}}</div>
<div class="col">{{arsenalStats[$index]['-won']}}</div>
<div class="col">{{arsenalStats[$index]['-drawn']}}</div>
<div class="col">{{arsenalStats[$index]['-lost']}}</div>
<div class="col">{{arsenalStats[$index]['-points']}}</div>
</div>
Any ideas?
using leagueTable object, you should be using val.
<div class="row" ng-repeat="val in leagueTable| limitTo:-1">
<div class="col">{{val[$index]['-played']}}</div>
<div class="col">{{val[$index]['-won']}}</div>
<div class="col">{{val[$index]['-drawn']}}</div>
<div class="col">{{val[$index]['-lost']}}</div>
<div class="col">{{val[$index]['-points']}}</div>
</div>
I have a html code which displays ads ,but the ads are display like a coloumn vise, but I want them to display in a horizontal row .How can we display the horizontal rows.And ads are which are coming dynamically based on the user selection.How can we display these ads in a row wise fashion .
Html code is :
<div class="row">
<div class="col-md-3" id="adsid"></div>
</div>
Code snippet from JS:
<input type="checkbox" id=' + s[i]['id']['0'] + ' />
<a href="#" class="list-group-item ">
<input type="hidden" id="adsid" name="adsrunning" value=' + s[i]['id']["0"] + '/>
<h4 class="list-group-item-heading">
<font color="blue">' + s[i]['hea']["0"] + '</font>
</h4>
<p class="list-group-item-text">' + s[i]['desc']["0"] + '</p>
<p class="list-group-item-text">' + s[i]['desc2']["0"] + '</p>
<p class="list-group-item-text">
<font color="green">' + s[i]['url']["0"] + '</font>
</p>
</a><br/>
And JS is :
$("#groupid").change(function () {
$("#adsid").html("");
var grpvalue = $("#groupid").val();
var accid = $('#accountid').val();
var adsarray = [];
$.ajax({
type: "post",
dataType: 'json',
url: "pages/ads.php",
data: "adgroup=" + grpvalue + "&accid=" + accid,
success: function (s) {
for (var i = 0; i < s.length; i++) {
var head = s[i]['hea']["0"];
//alert(head);
var adid = s[i]['id']["0"];
var desc1 = s[i]['desc']["0"];
var desc2 = s[i]['desc2']["0"];
var url = s[i]['url']["0"];
var p = document.createElement('p');
var txt = document.createTextNode(head);
p.appendChild(txt);
//$('adsid').append(p);
adsarray.push(head, adid, desc1, desc2, url);
$("#adsid").append("");
$("#adsid").append('<input type="checkbox" id=' + s[i]['id']['0'] + ' /><input type="hidden" id="adsid" name="adsrunning" value=' + s[i]['id']["0"] + '/><h4 class="list-group-item-heading"><font color="blue">' + s[i]['hea']["0"] + '</font></h4><p class="list-group-item-text">' + s[i]['desc']["0"] + '</p><p class="list-group-item-text">' + s[i]['desc2']["0"] + '</p><p class="list-group-item-text"><font color="green">' + s[i]['url']["0"] + '</font></p><br/>');
}
}
});
});
And Json Data is:
[{
"hea": {
"0": "Kidney Stone Removal"
},
"id": {
"0": "40602813172"
},
"desc": {
"0": "Get treated at top kidney center"
},
"desc2": {
"0": "Take a free advice from our experts"
},
"url": {
"0": "www.ainuindia.com"
}
}]
I think your questions i answered here:
http://www.w3schools.com/css/css_float.asp
Use float to place the "rows" next to each other.
Though i would recommend you to change your "row" class to something more appropriate if possible. Since row are explicitly saying that it's a row, in other words a vertical alignment.
You can use ul li tag as bellow give style to li as list-style:none
<div class="row">
<ul >
<li class="col-md-3 col-sm-3 col-xs-6"><img src="" /><span class="badge">Lorem ipsum</span></li>
<li class="col-md-3 col-sm-3 col-xs-6"><img src="" /><span class="badge">Lorem ipsum</span></li>
<li class="col-md-3 col-sm-3 col-xs-6"><img src="" /><span class="badge">Lorem ipsum</span></li>
<li class="col-md-3 col-sm-3 col-xs-6"><img src="" /><span class="badge">Lorem ipsum</span></li>
</ul>
</div>
If you can modify the html of ad, try replacing col-md-3 by col-sm12 so the whole thing would read:
<div class="row">
<div class="col-sm-12" id="adsid">
</div>
</div>
I'm assuming you're using bootstrap, so having col-md-3 makes it float left with width 33%. On medium screen.
I had a nested JSON object in this form
var termValues=[
{
clause_title:"One",
clause_id:"One",
CM_terms: [
{ termName: 'CompanyName', type:"text", termValue:"CompanyName1", termId:'1' },
{ termName: 'Contract termValue', type:"number", termValue:"1234",termId:'2' },
{ termName: 'Contract End', type:"date", termValue:"2012-02-02", termId:'3' }
]
},
{
clause_title:"Two",
clause_id:"Two",
CM_terms: [
{ termName: 'CompanyName', type:"text", termValue:"CompanyName2", termId:'4' },
{ termName: 'Contract termValue', type:"number", termValue:"5678",termId:'5' },
{ termName: 'Contract End', type:"date", termValue:"2011-02-02", termId:'6' }
]
}
];
I applied binding in this form
function TestModel (termValues)
{
var self=this;
self.Clauses=ko.observableArray(termValues)
}
ko.applyBindings(new TestModel(termValues),$("#ctrTerms1")[0]);
HTML code:
<div data-bind="foreach: Clauses" id="ctrTerms1">
<div class="panel">
<div class="control-bar panel-heading">
<h4 class="panel-title" style="overflow:auto">
<a class="col-md-12 clref">
<span class="clause-title" title="Click to edit" data-bind="text: Clauses.clause_title"></span>
</a>
</h4>
</div>
<div>
<div class="panel-body">
<form class="form-horizontal" role="form" data-bind="foreach: CM_terms">
<div class="form-group" >
<label class="col-md-2 control-label" data-bind="text: termName">Title</label>
<div class="col-md-9">
<input type="text" class="form-control cttermValue" id="clauseTitle" data-bind="value: termValue">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
Now the issue is if I have more than 1 term I CM_terms will be in the form of an Array so for-each of CM_terms will work, But if I have only 1 CM_terms (Single object), Knock out is not able to bind as CM_term will not be array.
var termValues=[
{
clause_title:"One",
clause_id:"One",
CM_terms:
{ termName: 'CompanyName', type:"text", termValue:"companyName1", termId:'1' }
];
How Can I make 'CM_term' values to convert to Array if it is a Single Object.
As of now I am Iterating termValues and making CM_terms to Array if its not an Array and then applying Bindings.
Is there any other way.
If you have single object then push it into array. In your case CM_terms always should be an array, no matter whether it has single object or multiple objects.
var termValues=[
{
clause_title: "One",
clause_id: "One",
CM_terms: [
{
termName: 'CompanyName',
type: "text",
termValue: "Cordys",
termId: '1'
}
]
];
Fiddle Demo
This is how we can solve the problem. Got a clue from one of the stack-over flow post(will post if found gain)
We can use data-bind="foreach:{data:$data.CM_Terms}". We get desired result even if CM_Terms is not an Array
<div class="panel-body" data-bind="foreach: {data:$data.CM_terms}">
JSFiddle