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>";
Related
I have successfully developed a cascading dropdown list using javascript thanks to some code I found online. The html code it generates looks as expected when I view the code inside my Firefox web developer tools. The problem I have is that my php backend cannot read this from the $_POST buffer. The error I get is "Undefined index". It's almost as if the php does not see the second DDL that is dynamically added to my html page. Is there a trick I'm missing?
<script type="text/javascript">
var created = 0;
function displayAccordingly() {
if (created == 1) {
removeDrop();
}
//Call mainMenu the main dropdown menu
var mainMenu = document.getElementById('mainMenu');
//Create the new dropdown menu
var whereToPut = document.getElementById('myDiv');
var newDropdown = document.createElement('select');
newDropdown.setAttribute('id',"newDropdownMenu");
newDropdown.setAttribute('name',"AccountNumber");
whereToPut.appendChild(newDropdown);
if if (mainMenu.value == "Office Expense") { //The person chose Office Expense
var option000000000=document.createElement("option");
option000000000.text="---";
option000000000.value="000000000";
newDropdown.add(option000000000,newDropdown.options[null]);
var option160006235=document.createElement("option");
option160006235.text="COPY PAPER AND SUPPLIES";
option160006235.value="160006235";
newDropdown.add(option1160006235,newDropdown.options[null]);
var option160006237=document.createElement("option");
option160006237.text="COPIER RENTAL AGREEMENT";
option160006237.value="160006237";
newDropdown.add(option1160006237,newDropdown.options[null]);
} else if (mainMenu.value == "Custodial") { //The person chose Custodial
var option000000000=document.createElement("option");
option000000000.text="---";
newDropdown.add(option000000000,newDropdown.options[null]);
var option164006410=document.createElement("option");
option164006410.value="164006410";
option164006410.text="CONTRACTED SERVICES-FACILITIES";
newDropdown.add(option164006410,newDropdown.options[null]);
var option164006415=document.createElement("option");
option164006415.value="164006415";
option164006415.text="MAINTENANCE-GROUNDS";
newDropdown.add(option164006415,newDropdown.options[null]);
var option164006420=document.createElement("option");
option164006420.value="164006420";
option164006420.text="MATERIALS AND SUPPLIES";
newDropdown.add(option164006420,newDropdown.options[null]);
}
created = 1
}
function removeDrop() {
var d = document.getElementById('myDiv');
var oldmenu = document.getElementById('newDropdownMenu');
d.removeChild(oldmenu);
}
</script>
What the development tools shows as my HTML code:
My PHP Code (simplified)
$AccountNumber = $_POST['AcountNumber'];
I can read Category from the $_POST buffer, but not AccountNumber.
I am thus thinking the Javascript works fine, I don't understand why the value for AccountNumber is not placed in the $_POST buffer.
The results from a print_r($_POST) is as follows (Right after [Category] I would expect [AccountNumber]=>):
Array ( [action] => POStepTwo [logged_in_user] => 1625605397 [who] => requester [UserID] => 1625605397 [Vendor] => 2080MED [Department] => Plant [Category] => Office Expense [ShippingInstructions] => 1 [RequesterNote] => test )
Thanks for all the help.
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();
I am trying to analyse some html code and break it into an array of objects.
Here is some example html code:
<slide data-time=5>
<div class="cds-block-title">Master Calendar</div>
<div class="cds-block-content">iframe to master calendar</div>
</slide>
<slide data-time=5>
<div class="cds-block-title">Weather</div>
<div class="cds-block-content">iframe to master Weather App</div>
</slide>
My goal is to break it down into an object similar to this:
[
{
"html":"<slide.....</slide>",
"time":"5",
"title":"Master Calendar",
"content":"iframe...."
},
{
"html":"<slide.....</slide>",
"time":"5",
"title":"Master Calendar",
"content":"iframe...."
}
]
I have tried a few different approaches.
Using Regex (This worked in my test, but not when I put it in production, the .match stopped working as expected, I also read a few posts stating that using regex to parse html code is not the best approach):
function splitSlidesHtml(html){
var html = '<slide data-time="5"><div class="cds-block-title">Activities & Sports</div><div class="cds-block-content">content</div></slide><slide data-time="5"><div class="cds-block-title">weather</div><div class="cds-block-content">content</div></slide>"';
var slides = html.match(/<slide.*?>(.*?)<\/slide>/g);
var slidesA = [];
if (!slides) {
slidesA.push({"html":html});
} else {
for (i in slides){
var c = {};
c.html = slides[i];
c.time = slides[i].match(/(data-time=)(.*?)>/)[2].replace(/['"]+/g, ''); // extract the time, and replace any quotes that might be around it
c.title = slides[i].match(/<div class="cds-block-title">(.*?)<\/div>/)[1];
c.content = slides[i].match(/<div class="cds-block-content">(.*?)<\/div>/)[1];
slidesA.push(c);
}
}
return slidesA;
} // end splitSlidesHtml
I have also tried using jQuery, which kind-of works, but I don't know enough about parseHTML to know how to make sure it breaks at the different slides.
var slides = $.parseHTML(html);
console.log(slides);
console.log(slides[0].innerHTML);
console.log(slides[0].outerHTML);
You can use $.parseHTML() to convert your HTML string into an array of DOM nodes and then loop over the nodes to grab the information you need. .map() is a good use in this case as you are mapping each node to something else.
var html = '<slide data-time=5>\
<div class="cds-block-title">Master Calendar</div>\
<div class="cds-block-content">iframe to master calendar</div>\
</slide>\
<slide data-time=5>\
<div class="cds-block-title">Weather</div>\
<div class="cds-block-content">iframe to master Weather App</div>\
</slide>';
var slides = $($.parseHTML(html)).map(function () {
return {
// store the HTML
html: this.outerHTML,
// store the data-time attribute
time: this.dataset.time,
// store the title
title: $('.cds-block-title', this).text(),
// store the content
content: $('.cds-block-content', this).text(),
};
}).get();
console.log(slides);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
This is what I finally came up with. I had trouble with map working to get the time correctly.
var html = sheetData['values'][prop]['html'];
var parsed = $.parseHTML(html);
var isSlide = true;
for (n in parsed){
var cur = parsed[n];
if (cur.nodeName == "SLIDE"){
var curSlide = {
html: cur.outerHTML, // store the HTML
time: cur.dataset.time, // store the data-time attribute
title: $('.cds-block-title', cur).html(), // store the title
content: $('.cds-block-content', cur).html(), // store the content
};
} else {
isSlide = false;
}
}
I have a button that needs to add some values to an object attribute. The problem I have found is that I'm creating new objects on every click.
And what I need is to add new values to a specific attribute of a specific object.
I'm getting this
Object { id=0, title="Rolling Stones", sessionsBegin="1443564000000"}
Object { id=0, title="Rolling Stones", sessionsBegin="1443564000001"}
Object { id=0, title="Rolling Stones", sessionsBegin="1443564000002"}
What I need to generate is this
Object { id=0, title="Rolling Stones",sessionsBegin="1443564000000, 1443564000001,1443564000002"}
This on the controller part:
$scope.addItem = function(indexItem, title) {
$scope.cart = {
"id" : indexItem,
"title" : title
}
if ($scope.cart.id==indexItem){
$scope.cart.sessionsBegin=$scope.sessions[indexItem].date;
console.log($scope.cart);
}
}
This on the partial view side:
<div class="row" >
<div class="large-6 columns" >
<div class="panel">
<div ng-repeat="session in sessions">
{{event.id}} Date: {{session.date }}  
Availability: {{session.availability}}  
<a ng-click="addItem($index, session.title);" ng-show="addMore">ADD </a>
</div>
</div>
</div>
</div>
You need to concat a string to your current value, like that:
// Add a comma if needed:
$scope.cart.sessionsBegin += ($scope.cart.sessionsBegin) ? ', ' : '';
// and then add the value itself:
$scope.cart.sessionsBegin += $scope.sessions[indexItem].date;
Btw. usually you'd want a list of those sessionsBegin values to be an array - it will be much easier to work with. In that case I'd suggest:
if (!$scope.cart.sessionsBegin) {
$scope.cart.sessionsBegin = [];
}
$scope.cart.sessionsBegin.push($scope.sessions[indexItem].date);
Wouldn't changing $scope.cart.sessionsBegin=$scope.sessions[indexItem].date; to $scope.cart.sessionsBegin+=$scope.sessions[indexItem].date; do the trick?
In your code you redefine the cart object every time you press 'add' though. Hence why your console.log shows new objects every time.
$scope.cart = { ... } // this bit of code means you delete the 'old' $scope.cart and redefine it with new values
Does this work for you?
$scope.addItem = function(indexItem, title) {
$scope.cart = $scope.cart || {
"id" : indexItem,
"title" : title
}
if ($scope.cart.id==indexItem){
var sessionAsArray = $scope.cart.sessionsBegin.split(',');
sessionAsArray.push($scope.sessions[indexItem].date);
$scope.cart.sessionsBegin=sessionAsArray.join(',');
console.log($scope.cart);
}
}
Pastebin of index.html: http://pastebin.com/kdKFqTxe
Just copy and paste that and run it (this works but with some broken img links & no css).
With regards to the pastebin, just click on a node, and then click the first broken image below the video. What should happen is a dialogue box should appear with links to articles (from tubeArray). All relevant code is pasted below.
I'm trying to dynamically change the contents of a div when I click an image. The image has it's respective id (the first index in the inner array) within the first inner array there's another array (index 3). I want to populate my div (id="articleLinks") with those links using JQuery when the image is clicked.
JavaScript & JQuery:
The tube array. *Note: the first index of each element in tubeArray is the ID & the news articles aren't linked to anything particular. Only interested in tubeArray[0] & tubeArray[4]
var tubeArray = [
['UQ', -27.495134, 153.013502, "http://www.youtube.com/embed/uZ2SWWDt8Wg",
[
["example.com", "Brisbane students protest university fee hikes"],
["example.com", "Angry protests over UQ student union election"],
]
],
['New York', 40.715520, -74.002036, "http://www.youtube.com/embed/JG0wmXyi-Mw",
[
["example.com" , "NY taxpayers’ risky Wall Street bet: Why the comptroller race matters"]
]
],
['To The Skies', 47.09399, 15.40548, "http://www.youtube.com/embed/tfEjTgUmeWw",
[
["example.com","Battle for Kobane intensifies as Islamic State uses car bombs, Syrian fighters execute captives"],
["example.com","Jihadists take heavy losses in battle for Syria's Kobane"]
]
],
['Fallujah', 33.101509, 44.047308, "http://www.youtube.com/embed/V2EOMzZsTrE",
[
["example.com","Video captures family cat saving California boy from dog attack"],
["example.com","Fines of £20,000 for dogs that chase the postman"]
]
]
];
A for loop which goes through each element in tubeArray then assigns id to the first index. Also an image that calls the function myFunctionId which takes the parameter this.id.
for (i = 0; i < tubeArray.length; i++) {
var id = tubeArray[i][0];
//other code
'<img src="img.png" onclick="myFunctionId(this.id);" id="' + id + '">' +
//other code
}
function myFunctionId (id) {
journal = id;
alert(journal) //just a test
//I want to search through tubeArray with the id and find the matching inner array.
//I then want to loop through the innerArray and append to my html a link using JQuery.
$('#articleLinks').append("<a href='"+innerArray[0]+"'>"+innerArray[1]+'</a>'); // use CSS to break lines
}
}
HTML:
<div id="articleLinks">
Example Link<br>
</div>
Any help would be greatly appreciated. I've tried to simplify & cut out as much as I can so it's readable.
try this...
function myFunctionId (id) {
console.log(tubeArray);
tubeArray.forEach(function(entry) {
if (entry[0]==id) {
entry[4].forEach(function(innerArray){
$('#articleLinks').append("<a href='"+innerArray[0]+"'>"+innerArray[1]+'</a>'); // use CSS to break lines
});
return;
}
});
}
it makes it look like this for me... you're gonna have to handle that encoding issue. with the apostrophe. there are a lot of ways to handle it...
so.... if it was me... which it's not. but if it was... i would use an associative array instead of a numerically indexed one because it's easier to read the code and understand what you're using and where and how and things and stuff.
tubeArray = {
'UQ' : { 'location': [-27.495134, 153.013502],
'youtube': "example.com/embed/uZ2SWWDt8Wg",
'articles': [["example.com/queensland/brisbane-students-protest-university-fee-hikes-20140521-zrk8o.html", "Brisbane students protest university fee hikes"],
["example.com/content/2012/s3578878.htm", "Angry protests over UQ student union election"], ]
},
'New York': { 'location': [0.715520, -74.002036],
'youtube': "example.com/embed/JG0wmXyi-Mw",
'articles': [["example.com/2014/10/19/ny-taxpayers-risky-wall-street-bet-why-the-comptroller-race-matters/" , "NY taxpayers’ risky Wall Street bet: Why the comptroller race matters"]],
},
}