I have a couple of divs that I created dynamically, which are added for documents that the user already seen.
doc_html.innerHTML = '<div id=' + doc_id + ' class="seen-doc"> <h5>You\'ve already seen this document.</h5></div>' + doc_html.innerHTML;
I also have this code to run when the user clicks the back button while on document, to return to the main menu. (I got this from https://stackoverflow.com/a/19196020/1122229)
<input type="hidden" id="refresh" value="no">
<script>
$(document).ready(function(e) {
var $input = $('#refresh');
$input.val() == 'yes' ? update_seen_docs() : $input.val('yes');
});
</script>
What I need update_seen_docs() to do is look at the dynamic divs that I created earlier (with id equal todoc_id) and check if they exist or not. I already have the list of doc_ids that I want to check their existence. What I need is a way to check whether these dynamic div been created successfully by my earlier code.
I have tried putting this in my update_seen_docs()
doc_html = document.getElementById(doc_id);
if (doc_html){
# do stuff
}
but since the divs with doc_id are dynamic, doc_html is always null.
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.
In my Sharepoint project/Web Part/Web Page, I dynamically create page elements/controls using C# in the *.ascx.cs file.
In the *.ascx file, I use jQuery for responding to events that happen on the page (selections, changes of checkbox states, etc.).
I have a need to conditionally invisiblize groups of controls/elements on the page. Specifically, if the user checks a certain checkbox, I can "remove" whole swaths of the page that, in that scenario, don't apply to her.
How can I do this? I've got this starting point:
/* If the select "Yes" (they are seeking payment for themselves, as opposed to someone else), omit (invisibilize) sections 2 and 3 on the form */
$(document).on("change", '[id$=ckbxPaymentForSelf]', function () {
var ckd = this.checked;
if (ckd) {
// what now?
}
});
I could do it the hair-pulling-out way (which would be very painful for me, because I have almost as much hair as Absalom did), and set each individual element, like so:
if (ckd) {
var $this = $('[id$=txtbxthis]');
var $that = $('[id$=txtbxthat]');
var $theother = $('[id$=txtbxtheother]');
. . . // store a reference to all the other to-be-affected elements in vars
$this.visible = false; // <= this is pseudoscript; I don't know what the jQuery to invisiblize an element is
$that.visible = false; // " "
$theother.visible = false; // " "
. . . // invisiblize all the other to-be-affected elements
}
Surely there's a more elegant/better way!
Is it a matter of assigning all the conditionally invisible elements a particular class, and then invisiblizing every element that is assigned that class, or what?
Also, I want the area formerly used by this now-invisible swath to "go away" or "roll up" not sit there with a blank stare, yawning chasm, or Gobi Desert-like featureless expanse.
there are a number of ways to do this. but in your jquery implementation I would decorate the elements with data tags that will tell the code which elements to hide and show.
<input data-group="1" type="text" />
<input data-group="2" type="text" />
var $group1 = $('*[data-group="1"]');
var $group2 = $('*[data-group="2"]');
if (ckd) {
$group1.hide();
$group2.show();
}
else{
$group2.hide();
$group1.show();
}
You could do the same thing with css classes as well but I prefer using the data attribute
If you can group your controls using classes, you could select the class which needs to be hidden in that particular scenario and just use the hide() function:
if (ckd) {
var cls = getClassForCurrentScenario();
$("." + cls).hide(); //slideUp() would be an animated alternative
}
If the controls can be grouped inside a div, for example, then you'd just need to hide that element:
if (ckd) {
var id = getElementIdForCurrentScenario();
$("#" + id).hide(); //slideUp() would be an animated alternative
}
It really depends on how you manage to group your controls into "target groups", so that you can efficiently access them later.
You can hide an element like so:
$('...').hide();
Or you can slide it up with:
$('...').slideUp();
to get a nice sliding up animation.
On a side note, you can do this to multiple elements at once, in your case:
$('[id$=txtbxthis], [id$=txtbxthat], [id$=txtbxtheother]').slideUp();
function createInput(id){
count++;
var name = "name" + count;
var text = "#" + id.id;
var newInput = "<input type='text' id='" + name + "' placeholder='' />";
var myTextArea = document.getElementById(id.id);
myTextArea.innerHTML += newInput;
return false;
}
The above function adds an input type to a textarea in a div in my code. Once the input type is displayed dynamically, i try to get it's element id using getElementById but it returns null. May I know what is going wrong here? It seems that the new input type is added but somehow the input type is null.
Also, when i refresh the page, i realize the newly added input type disappears. Any way to force the new dynamic input type to remain in the page?
A dynamically created content is only temporary on the page. When page is refreshed it is again without it. You should recreate it again on a page onload Event or .ready() (store the information in a cookie or HTML5 storage).
I tried to create working example of your code: http://jsfiddle.net/G2PKF/1/.
<div id="area1" onclick="createInput(this)" ></div>
<br/>
<div id="area2" onclick="createInput(this)"></div>
<input type="button" onclick="alert(document.getElementById('name' + count));alert(document.getElementById('name' + count).outerHTML)" value="Access Last Element" />
When a rectangle is clicked an input is added to it. The button allows to display last element added.
Everything works as expected. I don't see any problem with your function.
My page is moderately complicated and I'm fairly sure its the jquery acting weird. So i'll add the relevant content first and if anyone needs more info let me know and I'll provide it.
The premise is that there is a div which holds keyword bubbles. These bubbles have a tooltip (qTip plugin) with relevant info that you can select and deselect. Sometimes keywords have overlapping relevant info so when one is deselected all others need to be deselected at the same time. This list of bubbles is built dynamically via ajax and can continue to be added on to the page live.
The problem is that some of the check boxes don't uncheck when I click on them, but if I click on the same one in another tooltip it works... which also now lets the original one work just fine. I have no idea why some work and others dont. I figure it has to do with the way the live onlick function binding and/or selectors are written.
The following function writes the html content of the tooltip based on a json object, so just assume the content is there. The jquery code at the bottom is the function I have bound to the checkboxes.
function constructSpecializationsHTML(data){
var html = '';
for(i = 0; i < data.specializations.length; i++){
if(data.specializations[i].name != ''){
html += "<span class='is-specialization-line'>";
html += "<input class='is-specialization-checkbox' type='checkbox' name='" + data.specializations[i].name + "' checked='" + isSpecializationChecked(data.specializations[i].name) + "'/>";
html += "<span>" + data.specializations[i].name + "</span>";
html += "</span><br />";
} else {
html += "This keyword is not known in our ontology";
}
}
return html;
}
$(document).on("click", ".is-specialization-checkbox", function(){
var $checkboxs = $(".is-specialization-checkbox[name='" + $(this).attr("name") + "']")
$checkboxs.prop("checked", !$checkboxs.prop("checked"));
});
Firstly, when the click event fires the "checked" property has already been changed, meaning that the states of your checkboxes are different.
Changing
!$checkboxs.prop("checked")
To
$(this).prop("checked")
Solves that.
Secondly when you have only displayed one tooltip your select is only returning one checkbox. If you display all the tooltips before checking or unchecking it returns the correct number. My guess is that qTip isn't adding the html for the tooltip to the DOM until it is displayed.
That's why not all your similarly named checkboxes are unchecking though (At least I think that's it!)
$(document).on("click", ".is-specialization-checkbox", function(){
var $checkboxs = $(".is-specialization-checkbox[name='" + $(this).attr("name") + "']")
$checkboxs.not($(this)).prop("checked", false);
});
changed this to $(this) - that way it is the specific checkbox that was clicked that is getting excluded from the deselection.
I've never particularly used JS much, with the exception of basic animations,
The page I'm working on requires me to fade out the active div and fade the requested one in, I have around 25 different div's I'll be fading between. At the minute I can't think of how to only fade the active one out so I'm trying to fade every div but the one that's requested out.
Here's the code I'm attempting to get working
var active = 0;
for (i=0;i<array.length;i++) {
if (i != active){
document.write("$('."+array[i]+"').fadeOut(900);");
}
naturally i know the document.write shouldn't be there, but ideally that code has to be printed into the .js file I'm using, however. I don't have a clue how to print it to the .js.
any suggestions would be greatly appreciated, or a way to do this in php without a page reload!
When you find yourself generating code on the fly, it usually indicates that you want to take a step back and re-evaluate your approach. :-)
In this case, there's no need to create the JavaScript dynamically. It's just a matter of running the code.
I wasn't sure what your definition of "active" was, so here's something that fades divs in/out on the basis of what buttons you press:
The HTML:
<input type='button' value='1'>
<input type='button' value='2'>
<input type='button' value='3'>
<input type='button' value='4'>
<input type='button' value='5'>
<input type='button' value='6'>
<div id='container'>
<div class='c1'>This is c1</div>
<div class='c2'>This is c2</div>
<div class='c3'>This is c3</div>
<div class='c4'>This is c4</div>
<div class='c5'>This is c5</div>
<div class='c6'>This is c6</div>
</div>
The JavaScript (teaching version):
jQuery(function($) {
// Hook our buttons; this selector hooks all of them,
// so you probably want to narrow that down, but I
// have no idea what your definition of "active" is,
// so I made one up.
$(":button").click(function() {
// Get the value of the button, e.g., 1, 2
var val = this.value;
// Get all of the divs in the container
var divs = $("#container div");
// Fade out all of the ones that aren't our target;
// fade in the one that is
divs.not(".c" + val).fadeOut(900);
divs.filter(".c" + val).fadeIn(900);
});
});
Live copy
That does this:
Uses the jQuery ready function (the shortcut form where I just pass a function into the jQuery function) to run the code when the page is "ready" (the DOM has been built)
Looks up all divs we want to be dealing with. In my case, it's all the divs in a container, but you can use just about any CSS3 selector you want (and then some).
Uses not with a class selector to filter out the div that has the target class, then uses fadeOut to start fading the other ones out.
Uses filter to reduce the set to just our target div, and fadeIn to start fading it in.
That version is for clarity. Here's a more concise version (still perfectly clear to people who know jQuery well, but tricky for folks still finding their feet):
The JavaScript (chained version using end):
jQuery(function($) {
// Hook our buttons; this selector hooks all of them,
// so you probably want to narrow that down, but I
// have no idea what your definition of "active" is,
// so I made one up.
$(":button").click(function() {
// Get the value of the button, e.g., 1, 2
var val = this.value;
// Get all of the divs in the container
// Fade out all of the ones that aren't our target;
// fade in the one that is
$("#container div")
.not(".c" + val).fadeOut(900)
.end()
.filter(".c" + val).fadeIn(900);
});
});
Live copy
Not sure why you are using document.write instead of simply executing the javascript.
var active = 0;
for (i=0;i<array.length;i++) {
if (i != active) {
$("."+array[i]).fadeOut(900);
}
Additionally, try using a jQuery selector to select all the non-active divs by adding an additional class to each div:
var active = array[0];
var classname = "some_class";
$("div." + classname + ":not(." + active + ")").fadeOut(900);
You could even just select the visible divs that are not the active one and fade them out:
var active = array[0];
var classname = "some_class";
$("div." + classname + ":not(." + active + "):visible").fadeOut(900);