I have a firebase database with some information in it, that I just constructed a table:
rootRef.on("child_added", snap => {
var name = snap.child("leagueName").val();
var code = snap.key;
$("#table_body").append("<tr><td> <button id="+code+" class='mdl-button mdl-js-button'>"+ name +" </button></td></tr>");});
So now I have arbitrary number of rows at my table, each has a button with it's unique ID.
next step is that I want each of them to be a link to some other page.
Is there a way to retrieve these ID's to create a js click function with them?
I mean I don't know what these ID's are and how many of them will be, since this is something the user will enter.
Maybe there's another more efficient way?
I think you may be looking for:
$('#table_body').on('click', 'btn', function() {
alert($(this).attr('id'));
document.location = 'https:/your.new.url/leagues/' + $(this).attr('id');
});
Of course if you want the elements to just be a link to another page, you should really consider making them <a href='...'> elements, as those are the idiomatic way to model links to pages. And in that case, you could also simply inject the keys when you generate the row in the table:
$("#table_body").append("<tr><td> <a id="+code+" href='https:/your.new.url/leagues/"+code+"' class='mdl-button mdl-js-button'>"+ name +" </button></td></tr>");});
Related
this is the div im trying to copy
{%for i in current_user.posts%}
<div class = "own_posts" id = "{{'id_' + i.id|string}}">
<img src = "{{url_for('static',filename='user_prof_pic/' + current_user.prof_pic)}}">
{{current_user.first_name}}
<p>{{i.post}}</p>
<div class ="like_comment">
<ul>
<li>like</li>
<li>comment</li>
</ul>
</div>
<form class ="comment_form">
<input type="text" action = "#" name = "comment_box" class ="comment_box" id = "{{'id_' +i.id|string}}">
<input type="submit" value="comment" class ="submit" id = "{{'id_' + i.id|string}}">
</form>
</div>
{%endfor%}
so far I've been successful at prepending it and changing the newly prepended div's ID using jquery like this.
var count = 4
$(".submit").click(function(event){
event.preventDefault()
var id = $(this).attr("id")
var comment = $(".comment_box#" + id).val()
console.log(count)
count++
$.ajax({
type:"POST",
url:"#",//"{{url_for('main.ProfilePage',user = current_user.first_name)}}",
data: JSON.stringify({"comments":comment}),
contentType:"application/json;charset=UTF-8"
});
var div_copy = $(".own_posts#id_2").clone()
var div_copy2 = div_copy.attr("id","id_" + count)
$("#own_stream").prepend(div_copy2)
});
however the form ID within the prepended div still contains the ID of the div it was cloned from. to clarify
var div_copy = $(".own_posts#id_2").clone() the form in this div contains an id of id_2 so the newly prepended div's form id is still id_2
I changed the prepended div's ID doing this:
var div_copy = $(".own_posts#id_2").clone()
var div_copy2 = div_copy.attr("id","id_" + count)
$("#own_stream").prepend(div_copy2)
but I don't know how to access the form within this newly cloned div and change it's form ID.
how do we achieve this?
also am I doing this right? Im trying to learn web development and wan't to understand how sites like facebook,twitter etc. are showing your newly posted statuses/tweets into the page without refreshing it.
is what I'm doing the gist of how that works? if not
shed some light on a newbie
also this is just a test to practice the concepts
If all you are attempting to do is retrieve the form element using jQuery, based on your source, you have multiple options.
var form = $(".own_posts#id_2 > form");
/* or */
var form = $(".own_posts#id_2 > .comment_form");
I don't normally suggest the direct descendant method because if your genealogy changes in the future, it will fail. You are using templates so intuitively I see future changes to it a possibility. Using a unique identifier or known singular class and searching the entire div chain makes more sense to me.
var form = $(".own_posts#id_2 .comment_form");
/* or */
var form = $(".own_posts#id_2").find(".comment_form");
Those two options should be roughly equivalent for your purpose and can use either.
Also I would be careful with non-unique ids. You may get away with it by only searching smaller scoping chains, but you're only supposed to have one on the page. This is why most functions that retrieve by id will return only the first object found, rather than a collection.
I don't know how you're using the ids, but perhaps something like id="{{'posts_' + i.id|string}}" and so on to utilize unique prefixes.
I'm trying to find a way to get the ids from dragged divs after they are in the drop zone.
All the drag components have an id from drag1 - drag8 and the drop zone is div drop zone. Because there are no divs in the drop zone when the page loads I want to gather the ids on a save button for now with a text box entry and drop down menu select.
I have tried the code below:
$(document).ready(function() {
$("#dropzone div").click(function() {
var index = $("#dropzone div").index(this);
$("#dropzone_drag").html("Index " + drag + " was clicked");
});
});
And I use jQuery for the text box, which works nicely:
$(document).ready(function() {
$('#save').click(function() {
alert($('#name').val());
});
});
How do I find the ids from dragged divs after they are in the drop zone?
After playing around i came up with the following:
var ids = {};
$("#dropzone>div").each(function(i){
ids[i] = $(this).prop('id');
});
which at the moment says undefined, but i did manage to put it on the save button so it no longer pops up when i open the page.
Any suggests please?
In my comprehension .index(this) returns the index of the element relative to the list "#dropzone div"., which may or may not contain the elements in the order you want. But if all your elements have a common class, say ".foo_bar" it probably would be easier to know the id given an clicked element.
Otherwise, as you're using this on the function, if this is one of your "drags" it is probably easier to pick the id from this than to try the indexes.
Try doing it like that and maybe it'll word better.
ids = {};
$("#dropzone>div").each(function(){
ids[$(this).prop('id')] = $(this).prop('id').replace(/[^0-9]/g, '');
});
the code .replace() means that we are removing characters (in this case anything that isn't a number) from the string so we end up with it's true number. Instead of it's place in the DOM.
If i didn't comprehend well your problem, correct my comprehension errors and i will edit the answer. And an html of the zones would be nice ;)
The following code worked for me:
<script>
var div = document.getElementById('dropzone')
</script>
and on the button i added:
alert( div.innerHTML )
The result gave me all of the div information from it's html page so i could select the information i wanted to push to the database.
Thank you all for you input and advice.
Matthew
Via ajax i retrieve some json data, make it as html and append it to my page.
Here I have a problem. I cant access element by id, if id is variable.
For example, http://jsfiddle.net/f8g5e/1/
<div id="123">Hello</div>
<div id="321">Bye</div>
<div id="out"></div>
$(function(){
key = '123';
$('#' + key).hide();
$('#321').hide();
});
The simples thing is works! #123 and #321 elements are hidden. Yeah, it's pretty obviosly.
But, in my project, when I append data to page:
$('#123') //returns element
$('#' + key) //returns null
Some code:
// generating data
var htmlData = '<div id="123">Greetings!</div><div id="321">Bye bye</div>';
// appending data
$('#tweets').empty();
$('#tweets').append(htmlData);
What are the possible causes i can't access elements?
Thanks.
UPDATE
Dont know how it works in JSFiddle, but when I changed my IDs to properly names it began to work now. Thanks to all! Next time, I'll take more attention to w3c dom standarts ;) Happy New Year!
The only reason I can think of that $('#'+key) wouldn't work is because the variable key is undefined.
Note: you're not supposed to start an ID with a number according to the W3C spec. However, most browsers allow it, so I doubt this is causing your problem.
However, if you have two divs with the same ID attribute, then JavaScript will only select the first one it finds -- IDs are supposed to be unique. If this is happening, use classes instead.
You can either do this:
$(function() {
$('#321,#123').hide();
});
or you can do this:
$(function() {
var key = '123';
var doit = '321';
$('#' + key + ',#' + doit).hide();
});
I'm building a multi-feed RSS reader for school.
aList is the div that encompasses each individual feed (the amount of feeds will fluctuate).
theTitle is the div that will be filled with the attribute of the current feed. Additionally, if clicked, it will load a list of attributes from the current feed into theContent.
I'm wondering how I can dynamically load the attributes into theContent when theTitle is clicked, since theContent and theTitle are going to be non-unique divs (I can't give them IDs).
Thanks for your help in advance,
-Andrew
document.getElementsByClassName('aList').getElementsByTagName('div')
You should look into jQuery selectors for that and other DOM Manipulation. Something like
$("div.theContent").attr("name", "value");
by using jquery, you may use code like the following:
$(".theTitle").bind("click", function(){
$el = $(this);
$el.parent().$(".theContent").load('ajax/content.php?news=' . $el.text());
});
this will make all your links clickable, an on click, update their corresponding content divs with the value of ajax/content.php?news=theTitle-value
Use a nice Javascript library such as Prototype or jQuery. Seems petty now, but these frameworks save you tons of time in the long run.
In both frameworks, you can select that div with:
$('div.theTitle')
With jQuery, you can do:
$('div.theTitle').click( function() {
var title = $(this).text();
var contentDiv = $(this).siblings('div.theContent');
// Do something with contentDiv and the title
} );
This will make every theTitle div have an onClick event that does something with its associated theContent div.
<div class="aList">
<div class="theTitle" onclick="fillContentBox(this)"></div>
<div class="theContent"></div>
</div>
And in your script ...
function fillContentBox(div) {
var theContentDiv = div.parentNode.getElementsByTagName("div")[1];
// statements that do things with theContentDiv
}
You have to be able to determine which element you want to update if you don't want to update more than one. If the elements are grouped inside something else that does have an "id" value, you can take advantage of that.
How can i use javascript (i assume) to clone a table row like ive beautifully illustrated in the picture below?
You can hookup a live event to all the buttons. If you give them a class of clone for instance the following will work.
$('input.clone').live('click', function(){
//put jquery this context into a var
var $btn = $(this);
//use .closest() to navigate from the buttno to the closest row and clone it
var $clonedRow = $btn.closest('tr').clone();
//append the cloned row to end of the table
//clean ids if you need to
$clonedRow.find('*').andSelf().filter('[id]').each( function(){
//clear id or change to something else
this.id += '_clone';
});
//finally append new row to end of table
$btn.closest('tbody').append( $clonedRow );
});
Please Note:
If you have elements in the table row with id's you will need to do a .each through them and set them to a new value otherwise you will end up with duplicate id's in the dom which is not valid and can play havoc with jQuery selectors
You can do this like so
If you want a really simple solution, just use innerHTML:
var html = document.getElementById("the row").innerHTML;
var row = document.createElement('p');
row.innerHTML= html;
document.getElementById("table id").appendChild(row);
For what purpose do you want to use the data? I've done similar things previously on data input forms and generally I've found it to be beneficial to the users not to manipulate everything in Javascript but to hook to store the data on the server and interface with AJAX.
The issue is that as soon as you start letting users do this sort of complex table manipulation and they accidentally hit the back button you end up with a lot of disgruntled punters. Coding up transient storage on a database isn't that much harder than manipulating Javascript and in fact can be easier as you can break the operations down more easily. Debugging is simpler for that reason too (you always have inspect access to the current state of your table).
Lots of option for handling via AJAX - the simplest being to just use a place-holder division and feed the whole table structure in as needed.
A jQuery example:
$(document).ready(function(){
$('TABLE.recs').delegate('INPUT.clone','click',function(e){
e.preventDefault();
var s = $(this).parent().parent().clone().wrap('<div>').parent().html();
$('TABLE.recs TBODY TR:last').after(s);
});
});