I'm hooking into the Trello API and creating a with the Lists from a Board. I'm then attempting to list all the Cards from each List. When getting the ListID from the value attribute, it's returning "undefined". Why is this?
I'm printing it out with document.getElementById("demo").innerHTML = $(".board").val();
//HTML
<label>Choose from a List of Boards</label>
<div id="output"></div>
<label>Display Cards Below for Board Selected</label>
<div id="outputCards"></div>
<p id="demo"></p>
//Javascript
var $boards = $("<select>")
.attr("id", "boards")
.text("Loading Boards...")
.appendTo("#output");
Trello.get("/boards/BOARD_ID/lists", function(boards) {
$boards.empty();
$.each(boards, function(ix, board) {
$("<option>")
.attr({href: board.url, target: "trello", value : board.id, name : board.id, id : board.id})
.addClass("board")
.text(board.name)
.appendTo($boards);
});
});
var $cards = $("<div>")
.text("Loading Cards...")
.appendTo("#outputCards")
.appendTo("#demo");
// This is where I'm trying to return the value
document.getElementById("demo").innerHTML = $(".board").val();
var resource = "lists/LIST_ID/cards";
Trello.get(resource, function(cards) {
$cards.empty();
$.each(cards, function(ix, card) {
$("<a>")
.attr({href: card.url, target: "trello"})
.addClass("card")
.text(card.name)
.appendTo($cards);
});
});
The HTML is outputting like this:
<label>Choose from a List of Boards</label>
<div id="output">
<select id="boards">
<option target="trello" value="LIST_ID" name="LIST_ID" id="LIST_ID" class="board">
List One
</option>
...
</select>
</div>
<label>Display Cards Below for Board Selected</label>
<div id="outputCards"></div>
<p id="demo">undefined</p>
I think the main problem here is that the board class is only being added to elements in the Trello.get callback.
As this code is executed asynchronously, it's likely that you are executing $(".board").val() before the code in the callback has been executed, meaning `$(".board") returned no elements.
I would consider something like this
Trello.get("/boards/BOARD_ID/lists", function(boards) {
$boards.empty();
$.each(boards, function(ix, board) {
$("<option>")
.attr({href: board.url, target: "trello", value : board.id, name : board.id, id : board.id})
.addClass("board")
.text(board.name)
.appendTo($boards);
});
// This is where I'm trying to return the value
$('#board').change(function () {
document.getElementById("demo").innerHTML = $(".board:selected").val();
});
});
Related
Every time a selection is made from a dropdown menu, specific data is pulled from facebook and added to different divs. I am trying to update the contents of the div every time a different selection is made, however at the minute, the contents are just appended on after the initial contents.
This is the code that gets data based on a selection and creates the list from the returned data
<script>
city = document.getElementById("citySelection")
city.addEventListener("change", function() {
var selected = this.value;
var eventsList = document.getElementById("events");
if (selected == "None") {
eventsList.style.display = "none";
} else {
eventsList.style.display = "block";
};
if (selected == 'Bristol') {
getBristolEvents();
};
if (selected == 'Leeds') {
getLeedsEvents();
};
if (selected == 'Manchester') {
getManchesterEvents();
};
if (selected == 'Newcastle') {
getNewcastleEvents();
};
});
function createList(response, listId) {
var list = document.createElement('UL')
for (var i = 0; i < 10; i++) {
var events = response.data[i].name
var node = document.createElement('LI');
var textNode = document.createTextNode(events);
node.appendChild(textNode);
list.appendChild(node)
listId.appendChild(list);
}};
</script
This is the div being targeted:
<html>
<div id="events" style="display: none">
<div id="eventsDiv" style="display: block">
<div id="eventsListOne">
<h3 id='headerOne'></h3>
</div>
<div id="eventsListTwo">
<h3 id='headerTwo'></h3>
</div>
<div id="eventsListThree">
<h3 id='headerThree'></h3>
</div>
</div>
</div>
</div>
</html>
I have tried resetting the innerHtml of the div every time the function to get the data from facebook is called:
<script>
function getEventsThree(fbUrl, title) {
var listId = document.getElementById('eventsListThree');
var headerThree = document.getElementById('headerThree');
listId.innerHtml = "";
headerThree.append(title)
FB.api(
fbUrl,
'GET', {
access_token
},
function(response) {
listId.innerHtml = createList(response, listId)
}
)};
</script>
However, that still doesn't reset the contents of the div.
I've looked at other response but they all use jquery which I am not using.
Can anyone advise on the best way to fix this? Thanks.
I think your Hennessy approach is fine. Generate the inner content, then set .innerHTML.
At least one of your problems, maybe the only one, appears to be that you set .innerHTML to the return value of createList, but that function does not return anything.
Hollow i have some issue and small problem
i have 3 input fields I need to get values on click from them assign them to object and that object push in to array
can somebody can help ore say where to look info I'm searching on MDN but I can't find correct topic whit examples
1)input value to object and then that object push to array
function $(e) {
return document.querySelector(e);
}
function $$(e) {
return document.querySelectorAll(e);
}
var startBtn = $("send");
startBtn.addEventListener('click', creatTask, false);
function creatTask() {
var addTaskName = $(".task-name"),
addCategory = $(".category"),
addTaskSatus = $(".status");
<!-- task.Taskname = addTaskName.value
task.Category = addCategory.value
task.Status = addTaskSatus.value........... ? -- >
var TaskListArray = [];
var task = {
Taskname: undefined,
Category: undefined,
Status: undefined
}
console.log(task)
}
document.write("message")
Link to jsfiddle with html and javascript
Try setting id or className selector at var startBtn = $("send"); defining TaskListArray outside of creatTask function; setting values directly at creation of task object; use Array.prototype.push() to add current task object to TaskListArray array.
Also, use window.onload event, or place <script> after elements in html for elements queried in DOM to be loaded in document before creatTask is called or startBtn defined
<script>
window.onload = function() {
function $(e) {
return document.querySelector(e);
}
function $$(e) {
return document.querySelectorAll(e);
}
var startBtn = $(".send");
var TaskListArray = [];
startBtn.addEventListener('click', creatTask, false);
function creatTask() {
var addTaskName = $(".task-name"),
addCategory = $(".category"),
addTaskSatus = $(".status");
var task = {
Taskname: addTaskName.value,
Category: addCategory.value,
Status: addTaskSatus.value
}
TaskListArray.push(task)
console.log(task)
}
}
// document.write("message")
</script>
<input class="task-name" name="task" />
<br>
<input class="category" name="category" />
<br>
<input class="status" name="status" />
<br>
<input type="button" class="send" value="send" />
I have <option> tag with specific data-id="x" attribut. And I want to set the same attribute (data-id) of the option tag to the corresponding element (same html for example).
This is what I've done so far, yet I dont know why this is not working.
Can anybody help me on this?
JsFiddle
I guess the problem is that I don't specify which $('.cityName) shall get the attribute but I dont know how to specify because $(this) will refere to the each...
Here is the jQuery I'm using :
$('select option').each(function() {
var value = parseInt($(this).attr('data-id'));
var vals = (value+1); //This is optional
if($('.productsDispo .cityName').text() == $(this).text()){
$('.cityName').setAttribute('data-id', vals);
//$('.cityName').append(vals);
}
});
And here is the HTML
<select id="citySelector">
<option data-id="O">Bordeaux</option>
<option data-id="1">Paris</option>
<option data-id="2">Londres</option>
<option data-id="3">Téhéran</option>
</select>
<!-- Product List -->
<div class="productsDispo">
<div class="cityName">Bordeaux</div>
</div>
<div class="productsDispo">
<div class="cityName">Londres</div>
</div>
<div class="productsDispo">
<div class="cityName">Téhéran</div>
</div>
<div class="productsDispo">
<div class="cityName">Paris</div>
</div>
You need to use .each() two times, one nested to the other. For every <option> you need to check every div.cityName.
One thing to keep in mind is that in the inner .each() the variable this refers to the <div> and not the <option>. And that is why I use the $option variable.
$('select option').each(function () {
var $option = $(this);
var value = parseInt($option.attr('data-id'));
var vals = (value + 1);
$('div.cityName').each(function () {
if ($(this).text() == $option.text()) {
$(this).attr('data-id', vals);
}
});
});
Here is a demo
Here is what you trying to do ...
$('select option').each(function () {
var opt = this;
var value = parseInt($(opt).attr('data-id')) || 0;
var vals = (value + 1);
// Check the console Log
console.log("what you are excepting", $(opt).text());
console.log("what is Returning productsDispo .cityName", $('.productsDispo .cityName').text());
// if you check the console log you have to see you need to check for each
$('.productsDispo .cityName').each(function () {
var item = this;
if ($(item).text() == $(opt).text()) {
$(item).attr('data-id', vals);
//$('.cityName').append(vals);
}
});
});
but if i were you make it on different to avoid each i add an attribute which is named as data-bind-name for and html
<select id="citySelector">
<option class=".cityName" data-id="O">Bordeaux</option>
<option class=".cityName" data-id="1">Paris</option>
<option class=".cityName" data-id="2">Londres</option>
<option class=".cityName" data-id="3">Téhéran</option>
</select>
<!-- Product List -->
<div class="productsDispo">
<div class="cityName" data-bind-name="Bordeaux">Bordeaux</div>
</div>
<div class="productsDispo">
<div class="cityName" data-bind-name="Londres">Londres</div>
</div>
<div class="productsDispo">
<div class="cityName" data-bind-name="Téhéran">Téhéran</div>
</div>
<div class="productsDispo" data-bind-name="Paris">
<div class="cityName">Paris</div>
</div>
and Jquery code is
$('select option').each(function () {
var opt = this;
var value = parseInt($(opt).attr('data-id')) || 0;
var vals = (value + 1);
// Check the console Log
console.log("what you are excepting", $(opt).text());
console.log("what is Returning productsDispo .cityName", $('.productsDispo .cityName').text());
// if you check the console log you have to see you need to check for each
$('.productsDispo .cityName[data-bind-name='+$(opt).text()+']' ).attr('data-id', vals);
//$('.cityName').append(vals);
});
Using just one each and selecting the corresponding city with contains:
$("select")
.change(function () {
$("select option:selected").each(function () {
var city = $(this).text();
value = parseInt($(this).attr('data-id'), 10);
vals = (value + 1);
var item = $('.cityName:contains("' + city + '")');
item.attr('data-id', vals);
alert('data-id for ' + item.text() + ': ' + item.attr('data-id'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="citySelector">
<option data-id="0">Bordeaux</option>
<option data-id="1">Paris</option>
<option data-id="2">Londres</option>
<option data-id="3">Téhéran</option>
</select>
<!-- Product List -->
<div class="productsDispo">
<div class="cityName">Bordeaux</div>
</div>
<div class="productsDispo">
<div class="cityName">Londres</div>
</div>
<div class="productsDispo">
<div class="cityName">Téhéran</div>
</div>
<div class="productsDispo">
<div class="cityName">Paris</div>
</div>
This selector $('.productsDispo .cityName') will yield more than one element and hence you got to loop through it or jquery filter it to get the matched element and then set the attribute.
Alternate approach using data() method which reads data- attributes as well as stores in element dataset as a setter
var $cityOptions = $('#citySelector option');
$('.productsDispo .cityName').each(function(){
var $elem = $(this),
cityName = $.trim($elem.text()),
$option = $cityOptions.filter(':contains('+ cityName +')');
$elem.data('id', +$option.data('id') +1);
});
DEMO
I'm having a logic error with my code using angular js. What I have done is made a function that loops through a json array and returns the strings of the weather condition, eg
'clear',
'cloudy', etc...
It then checks to see if the value of the string is equal to another string. If it is, it returns an image link associated with the weather condition. The problem is that html ng-repeat function is repeating that one image and not any other image.
Here is the js:
var app=angular.module('app');
app.controller('MainCtrl', function($scope, $http) {
$scope.currentSydney = null;
$scope.currentMelbourne = null;
$scope.currentAdelaide = null;
$scope.currentDarwin = null;
$scope.currentBrisbane = null;
$scope.currentMelbourne = null;
$scope.currentCairns = null;
$http.jsonp('http://api.wunderground.com/api/5ad0204df4bdbeff/conditions/q/Australia/Melbourne.json?callback=JSON_CALLBACK').success(function(data){
$scope.currentMelbourne=data;
});
$http.jsonp('http://api.wunderground.com/api/5ad0204df4bdbeff/conditions/q/Australia/Sydney.json?callback=JSON_CALLBACK').success(function(data){
$scope.currentSydney=data;
});
$http.jsonp('http://api.wunderground.com/api/5ad0204df4bdbeff/conditions/q/Australia/Adelaide.json?callback=JSON_CALLBACK').success(function(data){
$scope.currentAdelaide=data;
});
$http.jsonp('http://api.wunderground.com/api/5ad0204df4bdbeff/conditions/q/Australia/Darwin.json?callback=JSON_CALLBACK').success(function(data){
$scope.currentDarwin=data;
});
$http.jsonp('http://api.wunderground.com/api/5ad0204df4bdbeff/conditions/q/Australia/Perth.json?callback=JSON_CALLBACK').success(function(data){
$scope.currentPerth=data;
});
$http.jsonp('http://api.wunderground.com/api/5ad0204df4bdbeff/conditions/q/Australia/Cairns.json?callback=JSON_CALLBACK').success(function(data){
$scope.currentCairns=data;
});
$http.jsonp('http://api.wunderground.com/api/5ad0204df4bdbeff/conditions/q/Australia/Brisbane.json?callback=JSON_CALLBACK').success(function(data){
$scope.currentBrisbane=data;
$scope.cityData=[
{ name:'Brisbane',
temp:$scope.currentBrisbane.current_observation.temp_c,
image:$scope.currentBrisbane.current_observation.icon
},
{ name:'Melbourne',
temp:$scope.currentMelbourne.current_observation.temp_c,
image:$scope.currentMelbourne.current_observation.icon
},
{
name:'Adelaide',
temp:$scope.currentAdelaide.current_observation.temp_c ,
image:$scope.currentAdelaide.current_observation.icon
},
{ name:'Darwin',
temp:$scope.currentDarwin.current_observation.temp_c ,
image:$scope.currentDarwin.current_observation.icon
},
{ name:'Perth',
temp:$scope.currentPerth.current_observation.temp_c ,
image:$scope.currentPerth.current_observation.icon
},
{ name:'Cairns',
temp:$scope.currentCairns.current_observation.temp_c,
image:$scope.currentCairns.current_observation.icon
},
]
for(y = 0 ; y < 6; y++){
var string = $scope.cityData[y].image;
console.log(string[10]);
}
});
$scope.iconString = function() {
switch ($scope.currentSydney.current_observation.icon) {
case 'partlycloudy' :
return 'pics/partlycloudy.png';
case 'clear' :
return 'pics/partlycloudy.png';
}
}
$scope.repeat = function() {
for(y = 0 ; y < 1; y++){
var string = $scope.cityData[y].image;
if(string=='mostlycloudy'){
return 'pics/mostlycloudy.png';
}
}
}
});
And here is the html:
<div id="weather-container">
<div id="current-weather">
<!--Angular JSON pull -->
<div id="title"><span id="current-title">Current Weather</span></div>
<div id="current-condition">{{currentSydney.current_observation.weather}}</div>
<img ng-src="{{iconString()}}"></img>
<div id="current-temp"><span id="current-temp"> {{currentSydney.current_observation.temp_c}} </span></div>
<span id="current-city">{{currentSydney.current_observation.display_location.city}} </span>
</div>
<!--Angular JSON pull and iteration-->
<div id="other-city-container">
<div class="other-city-weather" ng-repeat="city in cityData" >
<!--Image-->
<img ng-src="{{repeat()}}"></img>
<div class="current-city-temp">
<span>{{city.temp}}</span>
</div>
<div class="current-city-lower">
<span>{{city.name}}</span>
</div>
</div>
</div>
</div>
Now I'm calling the repeat function in the html inside the img src tag.
`
I see. You are making 2 loops : ng-repeat in the view, and a for loop in the controller ( repeat() ).
But I think that right now, they are not related to each other (which is what you need I guess): getting the index of the ng-repeat loop in your repeat method.
Try something like that :
In the view :
<img ng-src="{{repeat($index)}}" /><!-- Getting the current $index of the ng-repeat loop and passing it to the $scope.repeat() method -->
In the controller :
$scope.repeat = function(index) { // there, index becomes the value we just put in the view ($index = the current index of the ng-repeat loop), e.g. : 0,1,2,3...
var string = $scope.cityData[index].image; // We go get the right city in the cityData array, according to the current ng-repeat index.
// then we do the job
if(string=='mostlycloudy'){
return 'pics/mostlycloudy.png';
}
}
Not sure that works as I didn't test it, but you may know what I mean ?
I'm trying to find the deepest element in the specified divwith jquery. But the code which used is producing the error TypeError: parent.children is not a function.
I found this code from this link
the code is :
function findDeepestChild(parent) {
var result = {depth: 0, element: parent};
parent.children().each( //Here I getting the error TypeError: parent.children is not a function
function(idx) {
var child = $(this);
var childResult = findDeepestChild(child);
if (childResult.depth + 1 > result.depth) {
result = {
depth: 1 + childResult.depth,
element: childResult.element};
}
}
);
return result;
}
---------------------------------------------------------------------------------------
$(document).on('keypress','#sendComment', function(e) {
if(e.keyCode==13){
var itemId=$('#findbefore').prev('.snew').attr('id');//
var item=findDeepestChild(itemId);
alert(item);
}
});
And my divs are :
<div id="S04" class="snew" style="display: block;">
<div class="author-image"></div>
<span>xyz shared the image xyz</span>
<div class="s-content">
<div class="s-message"></div>
<div class="shpicture">
<img class="SharedImage" width="100%" height="100%" data-shareid="1" data-alid="1" data-id="1" alt="xyz" src="data:image/jpeg;base64,">
</div>
</div>
</div>
<div class="SPcommentbox">
<div class="comment">
<div class="commenter-image"></div>
<div class="addcomment">
<input class="commentbox" type="text" placeholder="Write a comment...">
</div>
</div>
</div>
I need to find the img from these.
please anyone help me .... Thanks ...
To get the deepest nested elements, use
$("#" + parent).find("*").last().siblings().addBack()
http://jsfiddle.net/6ymUY/1/
you can then get the id data attribute with
item.data("id")
http://jsfiddle.net/6ymUY/2/
full code:
function findDeepestChild(parent) {
return $("#" + parent).find("*").last().siblings().addBack();
}
var item=findDeepestChild("S04");
console.log(item)
console.log(item.data("id"));
You're calling it with a string, but it's expecting a jQuery instance.
Instead of
var itemId=$('#findbefore').prev('.snew').attr('id');//
var item=findDeepestChild(itemId);
you probably want
var item=findDeepestChild($('#findbefore').prev('.snew'));
You are passing in itemId, which is the ID attribute of a given element. I think what you meant to pass was the element itself. Just remove the attr call, leaving this:
var item = findDeepestChild($("#findbefore").prev(".snew"));