In my app I receive some objects in Json. I want to create one panel that shows a single object. If I receive 2 objects, create 2 panels with his content and if I receive 100: 100 panels.
I tried to use a for with .add and .doLayout but never shows any panel. In my console shows the creation of panels, but never renders into my principal panel container. What im doing wrong?
thats my code:
success : function(response) {
var jsonResp = Ext.util.JSON
.decode(response.responseText);
// Ext.Msg.alert("Info", "UserName from Server : " + jsonResp.message);
// Limpiamos el array para tener solo las propiedades que se usarán
jsonResp.forEach(function(currentItem) {
delete currentItem["cls"];
delete currentItem["estandar"];
delete currentItem["iconCls"];
delete currentItem["leaf"];
delete currentItem["objetivo"];
delete currentItem["observaciones"];
delete currentItem["porcentaje"];
delete currentItem["salvaguardas"];
delete currentItem["tieneDocs"];
delete currentItem["tipoNombre"];
delete currentItem["responsable"];
delete currentItem["responsableId"];
delete currentItem["idReal"];
delete currentItem["tipoNombre"];
delete currentItem["tipo"];
delete currentItem["calculado"];
delete currentItem["text"];
});
var children = [];
console.log(jsonResp);
var sumarvariable = 0;
//add children to panel at once
for ( var i in jsonResp) {
if (i < jsonResp)
var panel = new Ext.Panel({
id : 'pregunta' + sumarvariable,
html : sumarvariable
})
console.log(panel)
Ext.getCmp("contenedor").add(panel);
Ext.getCmp("contenedor").doLayout();
sumarvariable++;
}
},
Change that for and use a .forEach like you're using in your jsonResp.forEach under your second comment. This code creates one panel and add it to your "contenedor".
//Create Panel with every object
var i = 0;
jsonResp.forEach(function(currentItem) {
i++;
var panel = new Ext.Panel({
id: 'jsonObject' + i,
html: 'Object' + i
})
//Add to your object "contenedor"
Ext.getCmp("contenedor").add(panel);
});
//Force reload and shows every panel
Ext.getCmp("contenedor").doLayout();
Related
How are you?
Right now, I'm learning Arrays with Javascript. I've done a function to show a content of my array into a HTML file, but I only recive "undefined".
First of all, I tried to modify the code inside of "contenido", but I only received the "character" into the 0 position, like this example: contenido += "<div id=d"+posicion+">Titulo: "+serie.titulo[0]. It returned me "D", of Dexter.
What am I doing wrong?
This is my code.
/*Creating a class to structure the information of a TV show by saving the title, theme, array with the main actors and saving the favorite actor in the array.
*/
class SerieTV {
constructor (titulo, tematica, actoresPrincipales){
var arrayActores = new Array();
this.titulo=titulo;
this.tematica=tematica;
this.actores=actoresPrincipales;
/* Adding a function to generate a random favorite actor.
*/
this.generaActorFavorito = function(){
var long = actoresPrincipales.length;
let calc = Math.floor(Math.random()*(long));
arrayActores = actoresPrincipales[calc];
console.log(arrayActores);
}
}
}
/* Creating 3 series, the 1st with 2 actors, 2nd with 3 and 3rd with 4. Later, adding it to a new array called "total_series."
*/
var show01= new SerieTV('Dexter ', 'Drama ', ['Michael C Hall ' ,'Jennifer Carpenter']);
show01.generaActorFavorito();
var show02 = new SerieTV('Samurai Gourmet' , 'Cocina' , ['Naoto Takenaka' ,'Tetsuji Tamayama' , 'Honami Suzuki '] );
show02.generaActorFavorito();
var show03 = new SerieTV ('Breaking Bad ', 'Drama ', ['Aaron Paul ','Bryan Cranston ', 'RJ Mitte ', 'Anna Gunn ']);
show03.generaActorFavorito();
console.log("-------------------------");
var total_series = new Array();
total_series.push(show01);
total_series.push(show02);
total_series.push(show03);
console.log(total_series);
console.log("-------------------------");
/* Adding a button on HTML that when clicked, shows the information of all the series within the "total_series" array.
*/
function muestraArray(){
let contenido="";
total_series.forEach(function(serie, posicion){
contenido += "<div id=d"+posicion+">Titulo: "+serie[0]+"<br> Temática: "+serie[1]+" <br> Actor Favorito: "+serie[3]+" <br> Actores: "+serie[2]+" <br><br>";
});
document.getElementById("resultado").innerHTML = contenido;
}
Thanks!!
To access members of a class use dot notation syntax.
contenido += "<div id=d"+posicion+">Titulo: "+serie.titulo+"<br> Temática: "+serie.tematica+" <br> Actor Favorito: "+serie.actoresPrincipales+" <br> Actores: "+serie.actores+" <br><br>";
Also, inside the method generaActorFavorito in this statment arrayActores = actoresPrincipales[calc] you're reassigning an array to be a value which makes no sense, you can simply do var arrayActores; instead of var arrayActores = new Array();
Okey, problem solved. I solved that removing the square brackets. Thank you all!!
contenido += "<div id=d"+posicion+">Titulo: "+serie.titulo+"<br> Temática: "+serie.tematica+" <br> Actor Favorito: "+serie.actoresPrincipales+" <br> Actores: "+serie.actores+" <br><br>";
I have a project foreign key in by Phase model. I'm having hard time Create a dependent drop-down list inside my Django admin page.
I want to when user select a project from (project drop-down) phase of that project show in second dop-down
What would be the best way to achieve this?
It would be great if the dropdowns filter items based on the value of its parent.
class Project(models.Model):
name = models.CharFieldmax_length = 100, unique= True)
short_name = models.CharField(max_length= 4, unique= True)
slug = models.SlugField(max_length= 100, allow_unicode=True, null=True, editable= False)
location = models.OneToOneField(Location, on_delete = models.SET_NULL, null= True, blank= False, verbose_name= 'موقعیت')
start_date = models.DateField(default= timezone.now, null= True, blank= True)
end_date = models.DateField(default= timezone.now, null= True, blank= True)
duration = models.IntegerField(default= 0, editable= False)
class Phase(models.Model):
title = models.CharField(max_length= 20)
class ProjectPhase(models.Model):
project = models.ForeignKey(Project, on_delete= models.CASCADE, related_name= 'phase')
phase = models.ForeignKey(Phase, on_delete=models.CASCADE, related_name= 'project')
start_date = models.DateField(default= timezone.now)
end_date = models.DateField(default= timezone.now)
duration = models.IntegerField(default= 0, editable= True)
1. import a js media file in ModelAdmin for Generaldata:
class YourModelAdmin(admin.ModelAdmin):
form = YourModelForm
#list_display = ['your fields',]
class Media:
js = ("yourapp/selectajax.js",)
admin.site.register(YourModel, YourModelAdmin)
2. create a new js file which saved yourproject/yourapp/static/yourapp/ directory or another proper directory.
jQuery(function($){
$(document).ready(function(){
$("#id_project_select").change(function(){
// console.log(obj.currentTarget.value);
$.ajax({
url:"/get_phases/",
type:"POST",
data:{project: $(this).val(),},
success: function(result) {
console.log(result);
cols = document.getElementById("id_phase_select");
cols.options.length = 0;
for(var k in result){
cols.options.add(new Option(k, result[k]));
}
},
error: function(e){
console.error(JSON.stringify(e));
},
});
});
});
});
3. create a view to process ajax
#login_required
def get_phases(request):
project = request.POST.get('project')
phases = {}
try:
if project:
prophases = Project.objects.get(pk=int(project)).phase
phases = {pp.phase.title:pp.pk for pp in prophases}
except:
pass
return JsonResponse(data=phases, safe=False)
4. add 'get_phases/ to urlpatterns.
Notice that you should modify some codes as your need.
The answer by Blackdoor is a good approach and it's the one we just implemented, but it has a couple of problems:
It's only executed when you change the main select, and I wanted the dependant select to be filtered also on page load.
Does not keep que selected item in the dependant select.
In his solution, in step 2, replace his code with this one and adapt the names (I'm using service and sub_service instead of project / phase):
jQuery(function($){
$(document).ready(function(){
var clone = document.getElementById("id_sub_service").cloneNode(true);
$("#id_service").change(function(){
update_sub_services($(this).val(), clone)
});
update_sub_services($("#id_service").val(), clone)
});
function update_sub_services(service, clone) {
$.ajax({
url:"/chained_dropdowns/get_sub_services/",
type:"GET",
data:{service: service,},
success: function(result) {
var cols = document.getElementById("id_sub_service");
cols.innerHTML = clone.innerHTML
Array.from(cols.options).forEach(function(option_element) {
var existing = false;
for (var k in result) {
if (option_element.value == k) {
existing = true
}
}
if (existing == false) {
$("#id_sub_service option[value='"+option_element.value+"']").remove();
}
})
},
error: function(e){
console.error(JSON.stringify(e));
},
});
}
});
As you can see, now instead of removing all the items from the dependant select and then refilling it (which leaves you without the selected property and any other custom property), it removes the options that should not be there.
I'm not a JS developer and I don't know jQuery so my modifications are in native JS, please feel free to improve it :)
So I pull from a database a list of items and then display the titles as a list
global.screens.menu.search = function() {
var searchData = document.getElementById('search-input').value;
global.method.request('search-item', {title: searchData}, function(err, res) {// if() error handling logic}
// show new list of items.
else {
var list = document.createElement('ul');
for (var i = 0; i < res.list.length; i++) {
var item = document.createElement('li');
item.setAttribute('id', 'search-list-' + res.list[i].id);
item.appendChild(document.createTextNode(res.list[i].title));
list.appendChild(item);
}
document.getElementById('list').appendChild(list);
}
})
};
this created a list of items that look like
<li id="search-list-12">the first book</li>
<li id="search-list-16">the fourth book</li>
What I'm trying to do is make each of these items clickable (hyperlink) to a new page called product-page.html and pass the book ID so that I can display the book in the product page by the ID.
I was thinking of just setting session variable to the book ID then setting an href to "localhost://product-page" and on the redirect page load populate the page then delete the session variable. Not sure if that's the right approach.
in my product-page.html I have a function call that will populate everything. I just need to pass it an ID for the item.
global.screens.product.activate(id); //
I'm using an ExtJS grid panel. This grid has more than 20 rows of info and I want to search in each row for an icon that represents active mode, using WebdriverIO as a test driver.
How can I search in each row till the test driver finds the first active icon? (Note: the grid I'm testing is hosted on alegra.com).
Consider the following HTML print-screen:
It's hard to know exactly how to do it without knowing which locator you are using but if you first get a list of the rows and then filter them and grab the first match it should do what you are looking for.
public static get rows() { return browser.elements('#someTableId > table > tbody > tr'); }
public static getFirstMatch() {
return this.rows.value.filter((row: WebdriverIO.Element) =>
browser.elementIdElement(row.ELEMENT, 'someLocator').value)[0];
}
This is how i did it
var icon_type = 'delete';
it('Se elimina una factura', function(){
//rellenamos el array de elementos del grid
var elements = browser.getAttribute('#gridInvoices #gridview-1047-table tbody tr .action-icons img:nth-child(7)','class');
//Busca la primera coincidencia en el array con type
var row_num = elements.indexOf(icon_type);
if(row_num === -1){
throw new Error('No se encontraron botones activos del tipo "Eliminar" en todo el grid' )
}else{
$$('#gridInvoices #gridview-1047-table tbody tr')[row_num].click('.action-icons [title="Eliminar"]');
browser.click('=Sí')
};
});
I'm dynamically generating a list of checkboxes based on the contents of json data:
Format of tempfairway:
[{"FairWay":"A"},{"FairWay":"B"}, {"FairWay":"C"}, {"FairWay":"D"}]
var topics = tempfairway;
var topicContainer = $('ul#fairway_list');
$.each(topics, function (iteration, item) { topicContainer.append(
$(document.createElement("li")).append(
$(document.createElement("input")).attr({
id: 'topicFilter-' + item,
name: item,
value: item,
type: 'checkbox',
checked: true
})
//onclick
.click(function (event) {
var cbox = $(this)[0];
alert(cbox.value);
})
).append(
$(document.createElement('label')).attr({
'for': 'topicFilter' + '-' + item
}).text(item)
)
)
});
The checkboxes generate fine with the correct number but i'm getting [object Object] instead of the name of the fairway.
Any ideas on how to fix this?
Couple of more questions to add to this:
-What if i wanted to display ONLY unique values in tempfairway?
-.Click is set to get the value of that single checkbox, what if i want to iterate through all the checkboxes and get the value of all the ones that were selected in the case that the user unselected any of them?
In the line:
> $.each(topics, function (iteration, item) {
item is an object like {"FairWay":"A"}, so where you have:
> .text(item)
you probably want:
.text(item.FairWay)
and similarly for other uses of item. Or you could store the value in a variable and use that:
var fairwayName = item.FairWay;
...
.text(fairwayName);