I try actually to create a Simple Div Constrct based on a JS Array...
Unfortunately my Way below just shows up the Last Group / Element of the Array, what must be changed to create a repeating Div Construct for each Array Element?
Generated REsult should be like:
<div id="accordion">
<h3>'val.labelfromelement1'</h3>
<div class="notimportant">'val.Namefromelement1'</div>
<h3>'val.labelfromelement2'</h3>
<div class="notimportant">'val.Namefromelement2'</div>
<h3>'val.labelfromelement3'</h3>
<div class="notimportant">'val.Namefromelement3'</div>
<h3>'val.labelfromelement4'</h3>
<div class="notimportant">'val.Namefromelement4'</div>
</div>
Here is my actual Code:
var myData = [
{
label: "erster",
id: 0,
Name:"Ein Name"
},
{
label: "zweiter",
id: 1,
Name:"Der zweite Name"
},
{
label: "dritter",
id: 2,
Name:"Dritter Name"
}
]
$(document).ready(function(e) {
$.each(myData, function (i, val) {
myAccordion = "<h3>" + val.label + "</h3><div>" + val.Name + "</div>";
});
$("#myAccordionDiv").html(myAccordion);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<div id="myAccordionDiv">
</div>
</body>
as you can see, it should result in an accordion that will be automatic increase if a we create a new element in the array (The Array is from a chart)
Any Suggestion? Thank you for your help!
The reason you only see the last one is because you never initialize the variable myAccordionDiv and append each html string in the iterations to it.
Fiddle: http://jsfiddle.net/hz0b6k71/
var myAccordion = "";
$.each(myData, function (i, val) {
myAccordion += "<h3>" + val.label + "</h3><div>" + val.Name + "</div>";
});
$("#myAccordionDiv").html(myAccordion);
Your code is good but you have to append all the content of array to"myAccordion" var.
If you change your js code like this it will work.
$(document).ready(function(e) {
var myAccordion;
$.each(myData, function (i, val) {
myAccordion += "<h3>" + val.label + "</h3><div>" + val.Name + "</div>";
});
$("#myAccordionDiv").html(myAccordion);
});
I hope that will help you
Try appending variable myAccordion to #myAccordianDiv element within $.each()
var myData = [{
label: "erster",
id: 0,
Name: "Ein Name"
}, {
label: "zweiter",
id: 1,
Name: "Der zweite Name"
}, {
label: "dritter",
id: 2,
Name: "Dritter Name"
}
];
$(document).ready(function(e) {
$.each(myData, function(i, val) {
var myAccordion = "<h3>" + val.label + "</h3><div>" + val.Name + "</div>";
// append `myAccordion` string to `#myAccordionDiv`
$("#myAccordionDiv").append(myAccordion);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<div id="myAccordionDiv">
</div>
</body>
Here's an approach with raw javascript:
http://jsbin.com/nofiqiweri/edit?html,js,console,output
you were not storing the data into the myAccordion variable properly.
var myData = [
{
label: "erster",
id: 0,
Name:"Ein Name"
},
{
label: "zweiter",
id: 1,
Name:"Der zweite Name"
},
{
label: "dritter",
id: 2,
Name:"Dritter Name"
}
];
var myAccordion;
for (var i=0; i<myData.length; i++) {
myAccordion += '<h3>'+myData[i].label+'</h3><div>'+myData[i].Name+'</div>';
}
document.getElementById('myAccordionDiv').innerHTML(myAccordion);
Bts something like that, could get it run in those few minuts: :/ But look for AngularJS and fill an Object or even better JSON-Object into a table.
Some good Tutorials for this:
http://www.w3schools.com/angular/angular_tables.asp
http://jsfiddle.net/mjaric/pj5br/
var myData = [{
label: "erster",
id: 0,
Name: "Ein Name"
}, {
label: "zweiter",
id: 1,
Name: "Der zweite Name"
}, {
label: "dritter",
id: 2,
Name: "Dritter Name"
}
]
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$scope.names = myData;);
});
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>BlaBlaBla</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
<div ng-controller="customersCtrl">
<div ng-repeat="x in names">
<h3>{{x.Name}}</h3>
</div>
</div>
</body>
</html>
Related
I want to highlight the kendo grid cell by matching an external string text.
I googled a lot but found only searching a string in a particular column.
below is the code which works for one column
$("#grid").kendoGrid({
selectable: "multiple cell",
allowCopy: true,
columns: [
{ field: "productName" },
{ field: "category" }
],
dataSource: [
{ productName: "Tea", category: "Beverages" },
{ productName: "Coffeete", category: "Beverageste" },
{ productName: "Ham", category: "Foodte" },
{ productName: "Bread", category: "Food" }
]
});
var grid = $("#grid").data('kendoGrid');
var value = 'te';
var regex = new RegExp(value, "gi");
var colIndex = 0;
grid.tbody.find('tr[data-uid]').each(function () {
var td = $(this).find('td:eq(' + colIndex + ')');
var item = grid.dataItem(this);
td.html(item.productName.replace(regex, '<span style="background-color:yellow">' + value + '</span>'));
});
But I want the search the string text across all columns.
Can anyone help me on this?
The best for doing that IMO is to use templates, e.g.:
template: "#= findText(data.fieldName) #"
The template will use a function to create the search highlight which can be something similiar as you already done:
var findText = function findText(text) {
let index = text.indexOf(value),
result = text;
// If substring is found in current text
if (index > -1) {
let regex = new RegExp(value, "gi");
result = result.replace(regex, '<span style="background-color:yellow">' + value + '</span>');
}
return result;
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled</title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.common.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.rtl.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.default.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.mobile.all.min.css">
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.3.1023/js/angular.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.3.1023/js/jszip.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.3.1023/js/kendo.all.min.js"></script></head>
<body>
<div id="grid"></div>
<script>
var value = 'co';
var findText = function findText(text) {
let index = text.toLowerCase().indexOf(value),
result = text;
// If substring is found in current text
if (index > -1) {
let regex = new RegExp(`(${value})`, "gi");
result = result.replace(regex, '<span style="background-color:yellow">$1</span>');
}
return result;
};
$("#grid").kendoGrid({
selectable: "multiple cell",
allowCopy: true,
columns: [
{ field: "productName", template: "#= findText(data.productName) #" },
{ field: "category", template: "#= findText(data.category) #" }
],
dataSource: [
{ productName: "Tea", category: "Beverages" },
{ productName: "Coffeete", category: "Beverageste" },
{ productName: "Ham", category: "Foodte" },
{ productName: "Bread", category: "Food" }
]
});
</script>
</body>
</html>
Demo in Dojo
Hi i wanna display some values of an object,
the object has the next structure:
{
0:
{ id: "value",
topic: "value",
description: "value",
...
}
1:
{
...
}
}
and this is my code for display in a table with id=cursos
it has an ajax call before so I do this inside .done() method
the thing is that when I use double each to call teh first object and display its attributes it doesn't show anything, but when I call them by its name, without $.each() it is showed in table format,
How can I show the values of my objects in table format using $.each(), just to save code lines note: i have also changed the .html() for .append() and it's the same result.
resultado.done(
function (data){//success
$("#cursos").append($("<tr>").append(
$("<td>").append("Tema"),
$("<td>").append("Indice"),
$("<td>").append("DescripciĆ³n"),
$("<td>").append("Fecha"),
$("<td>").append("Idioma"),
$("<td>").append("Imagen"),
$("<td>").append("Enlaces"),
$("<td>").append("Nivel"),
$("<td>").append("Palabras clave"),
$("<td>").append("Autor"),
$("<td>").append("Escuela"),
$("<td>").append("Categoria"),
$("<td>").append("Subcategoria")
),
$("<tr>").html(
$.each(data, function (key, data1) {
$.each(data1, function (index, datos) {
console.log("index", datos);
$("<td>").append(datos);
})
})
/* if this block comment is removed it works
$("<td>").append(data[0].tema),
$("<td>").append(data[0].indice),
$("<td>").append(data[0].descripcion),
$("<td>").append(data[0].fecha),
$("<td>").append(data[0].idioma),
$("<td>").append(data[0].imagen),
$("<td>").append(data[0].enlaces),
$("<td>").append(data[0].nivel),
$("<td>").append(data[0].keywords),
$("<td>").append(data[0].autorId),
$("<td>").append(data[0].escuelasId),
$("<td>").append(data[0].categoriaId),
$("<td>").append(data[0].subcategoriaId)*/
)
);
//data[0].tema
}//function DONE
);//done
Try something like this:
var dataCollection = {
0: {
id: "id0",
topic: "topic0",
description: "desc0"
},
1: {
id: "id1",
topic: "topic1",
description: "desc1"
},
2: {
id: "id2",
topic: "topic2",
description: "desc2"
}
};
$.each(dataCollection, function(index) {
$("table#cursos").append("<tr>");
$.each(dataCollection[index], function(key, value) {
$("table#cursos").append("<td>" + value + "</td>");
});
$("table#cursos").append("</tr>");
});
See fiddle.
Hope this helps!
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8"/>
<!--http://stackoverflow.com/a/8563020/3200163-->
<!--http://stackoverflow.com/questions/8562744/how-to-loop-through-this-nested-object-json-array-and-build-an-html-string-with-->
</head>
<body>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script>
var data = {
"sEcho": 1,
"total": "1710",
"aaData": [
[
"Help",
"http:\/\/www.mysite.com\/wp-content\/uploads\/2011\/09\/dt_intfc4e732d1f1276d_4e76fab1e95bd.mp3?King_of_Spain_Entropy_02_Animals_Part_1.mp3",
"1784",
"3",
0,
null,
"0000-00-00 00:00:00"
],
[
"A Day In The Life",
"http:\/\/www.mysite.com\/wp-content\/uploads\/2011\/09\/dt_intfc4e732d1f1276d_4e76f5fc253a1.mp3?JenWood_Zeppelin.mp3",
"3573",
"3",
0,
null,
"0000-00-00 00:00:00"
]
]
}
var str = "";
for (var item in data.aaData) {
str += '<tr>';
for (idata in data.aaData[item]) {
str += '<td>' + data.aaData[item][idata] + '</td>';
}
str += '</tr>';
}
$('body').append("<table>" + str + "</table>");
</script>
</body>
</html>
This code creates a table correctly :)
I'm using AngularJS and I have a table that I populate using ng-repeat. Check this short example:
http://jsfiddle.net/sso3ktz4/
How do I check how many rows I have with a certain value? For example, in the fiddle above, how do I check how many rows I have with the word "second"? It should return "3".
AngularJS answers are preferred, although I also have JQuery available.
Thanks!
updated controller code is below, where $scope.findRowCount is required function
var myApp = angular.module('myApp', []).controller('MyCtrl', MyCtrl);
function MyCtrl($scope) {
$scope.items = [{
name: 'first',
examples: [{
name: 'first 1'
}, {
name: 'first 2'
}]
}, {
name: 'second',
examples: [{
name: 'second'
}, {
name: 'second'
}]
}];
$scope.findRowCount=function(value){
var count=0;
angular.forEach($scope.items, function(item, i){
if(item.name==value){
count=count+1;
}
angular.forEach(item.examples, function(exp, j){
if(exp.name==value){
count=count+1;
}
})
});
console.log("count"+count);
return count;
}
var result=$scope.findRowCount("second");
console.log(result);
}
http://jsfiddle.net/p3g9vyud/
Try this way
var myApp = angular.module('myApp', []).controller('MyCtrl', MyCtrl);
function MyCtrl($scope) {
$scope.items = [{
name: 'first',
examples: [{
name: 'first 1'
}, {
name: 'first 2'
}]
}, {
name: 'second',
examples: [{
name: 'second'
}, {
name: 'second'
}]
}];
//Get sum based on the label
$scope.getTotalByLabel = function(keyword)
{
$scope.totalSecond = 0;
angular.forEach($scope.items, function(value, key) {
if(value.name == keyword)
{
$scope.totalSecond += 1;
}
angular.forEach(value.examples, function(val, k) {
if(val.name == keyword)
{
$scope.totalSecond += 1;
}
});
});
return $scope.totalSecond;
}
}
th,
td {
padding: 7px;
text-align: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<table border="1">
<tbody ng:repeat="i in items">
<tr>
<td>{{i.name}}</td>
<td>{{$index}}</td>
</tr>
<tr ng:repeat="e in i.examples">
<td>{{e.name}}</td>
<td>{{$index}}</td>
</tr>
</tbody>
</table>
<b>Total of second</b>: {{getTotalByLabel('second')}}
</div>
</div>
I am new to AngularJs and I am curious on what is the best approach to getting then index of an ngrepeat on an input and comparing to see if the new string is different from the original value:
js:
var checkIfDataSampleHasChanged = document.getElementById('dsField' + i).value;
console.log(checkIfDataSampleHasChanged);
console.log($scope.currentSchema)
if (checkIfDataSampleHasChanged != $scope.currentSchema.sDataSamples.dsName) {
console.log("hello there")
$scope.currentSchema.sDataSamples.dsName = checkIfDataSampleHasChanged;
}
html:
<fieldset ng-repeat="ds in currentSchema.sDataSamples track by $index">
<label for="{{dsField$index}}" style="width:400px;">
Data Sample Name ({{ds.dsFileName}}):</label>
<input name="{{dsField$index}}" type="text" style="width: 400px;" ng-model="currentSchema.sDataSamples[$index].dsName" value="{{ds.dsName}}" />
<br>
<br>
</fieldset>
You can use a data to hold the initial value and then compare the changed value. You can do this in pure angularjs constructs without using document.getElementById and other hacks:
angular
.module('app', [])
.controller('AppController', function ($scope) {
var initialSample = [
{id: 1, name: 'Abc'},
{id: 2, name: 'def'},
{id: 3, name: 'ghi'},
{id: 4, name: 'jkl'},
{id: 5, name: 'mno'}
];
$scope.sample = angular.merge([], initialSample);
$scope.checkIfValueChanged = function ($index) {
var isValChanged = initialSample[$index].name !== $scope.sample[$index].name;
console.log(isValChanged);
if (isValChanged) {
alert("Value has changed");
} else {
alert("Value has not changed");
}
};
$scope.changeVal = function(){
var randInt = Math.floor(Math.random() * 5);
console.log(randInt);
$scope.sample[randInt].name = "Lorem ipsum";
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<div ng-app='app' ng-controller='AppController'>
<ul>
<li ng-repeat="item in sample" ng-click="checkIfValueChanged($index)">
{{item.name}}
</li>
</ul>
<button ng-click="changeVal()"> Change random value </button>
</div>
I want to create an Index in Elasticsearch using Javascript.
The name of each column is in a different position of an array and every field of each row in another array. How should I "fill" the body of the index?
Let's say a have:
arr_1 = [row1, row2, row3, row4];
arr_2 = [field1, field2, field3, field4];
then I want something like:
client.index(
index: name_index,
type: name_type,
body: {
row1 : field1; //arr1_[1] : arr_2[1],
row2 : field2; //arr1_[2] : arr_2[2],
.....
....
}
)
This seems to accomplish what you want, if I'm understanding you correctly:
var arr_1 = ["row1", "row2", "row3", "row4"];
var arr_2 = ["field1", "field2", "field3", "field4"];
var doc_body = {};
arr_1.map(function(val, idx){ doc_body[val] = arr_2[idx]; });
client.index({
index: 'test_index',
type: 'mytype',
id: '1',
body: doc_body
});
Here is a self-contained html document that implements it:
<html>
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/elasticsearch/3.0.2/elasticsearch.jquery.min.js"></script>
</head>
<body>
<div><button id="delete_index_btn">Delete Index</button></div>
<div><button id="create_index_btn">Create Index</button></div>
<div><button id="add_docs_btn">Add Docs</button></div>
<div>
<h3>Response:</h3>
<pre id="response"></pre>
</div>
<script type="text/javascript">
$(function(){
var client = new $.es.Client({
hosts: 'localhost:9200'
});
$("#delete_index_btn").click(function(){
client.indices.delete({
index: 'test_index'
}).then(function(resp){
$("#response").append("\nclient.indices.delete: " + JSON.stringify(resp));
}, function(err){
$("#response").append("\nclient.indices.delete ERROR: " + JSON.stringify(err));
});
});
$("#create_index_btn").click(function(){
client.indices.create({
index: 'test_index'
}).then(function(resp){
$("#response").append("\nclient.indices.create: " + JSON.stringify(resp));
}, function(err){
$("#response").append("\nclient.indices.create ERROR: " + JSON.stringify(err));
});
});
$("#add_docs_btn").click(function(){
var arr_1 = ["row1", "row2", "row3", "row4"];
var arr_2 = ["field1", "field2", "field3", "field4"];
var doc_body = {};
arr_1.map(function(val, idx){ doc_body[val] = arr_2[idx]; });
client.index({
index: 'test_index',
type: 'mytype',
id: '1',
body: doc_body
}).then(function(resp){
$("#response").append("\nclient.index: " + JSON.stringify(resp));
}, function(err){
$("#response").append("\nclient.index ERROR: " + JSON.stringify(err));
});
});
});
</script>
</body>
</html>
Does that solve your problem?
Thank you, I solved using this:
var doc_body= {};
for(i = 0; i = arr_1.length; i++){
doc_body[arr_1[i]] = arr_2[i];
}
client.index({
index: 'test_index',
type: 'mytype',
id: '1',
body: doc_body
});