Jquery cannot get id from django generated element - javascript

I am trying to retrieve an elements ID on click. The element is a div generated by django:
{% for artist in artists %}
<div class="band_box_inner" id='artist_{{artist.id}}' style="background-image: url({{artist.pic_primary.url}})">
</div>
{% endfor %}
The element is correctly displayed on the page. I am trying to retrieve the elements ID when it is clicked:
$('html').on('click', '.band_box_container', function() {
alert($(this).attr('id'));
});
However, every time this function alerts "undefined".
When I use:
$('html').on('click', '.band_box_container', function() {
alert($(this).html());
});
I correctly get the html of the element, including the id.
Why is my jquery selector not picking up the django generated template tag elements.attributes?

Looks like your Ids do not match.
band_box_inner vers band_box_container

Related

use jQuery.each() method to show hidden elements

I run a loop and create filters, which I pack in categories (packed in <ul>). These filters can be activated with checkboxes (packed in <li> within the <ul>). I can have 2 or 5 category filters, so 2 or 5 <ul> with multiple <li> inside each. With css all <li> checkboxes above 3 are hidden at start, and I use a "show more" element (in <span>) that is located just before </ul>.
As it's a loop, all <ul> elements use the same id="filterlist" and class="sidebar-ul". Also all the <li> checkboxes have the same class="sidebarfilters".
I have a JQuery each function, and on click on one of the <span> I only want to show the hidden <li> elements, that are placed within the <ul> element, in which also the clicked span is located.
At the moment, if I click on one of the "show more" spans, all <li> checkboxes of all <ul> are shown.
Is there a way (maybe with "$(this)") somehow to show only the correct <li>, even though classes are the same?
Also, I want to hide the "show more" span if all <li> elements are shown, this is not working as well. The <span> stays visible after all checkboxes are shown. Any input would be very much appreciated. My simplified code, CSS and JQuery are:
{% for tag in tags %}
<ul id="filterlist" class="sidebar-ul">
{% if current_tags contains tag %}
<li class="sidebarfilters">
<input class="filter_checkbox" id="checked" type="checkbox" checked onClick="">
</li>
<span class="showmorefilters">mehr...</span></ul>
</ul>
{% endfor %}
$(function() {
$(".showmorefilters").each(function() {
$(this).click(function() {
$('#filterlist li:hidden').show();
if ($('#filterlist li').length == $('#filterlist li:visible').length) {
$(this).hide();
}
});
});
});
.sidebarfilters:nth-child(n+5) {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Sounds like content is being created dynamically. Would advise using .on() versus .click(). Have to make a lot of assumptions without proper example.
Consider the following.
$(function() {
$("ul[id^='filterlist']").on("click", ".showmorefilters", function(e) {
var fl = $(this).parent();
fl.find("li:hidden").show();
if ($('li', fl).length == $('li:visible', fl).length) {
$(this).hide();
}
});
});
This will bind a Click event to all .showmorefilters elements and perform a callback that is relative to that target.

django with basic Jquery not responding

I have a django project which I implemented a jquery function to toggle a link but it is not working. the link does not display the hidden contect i want it to display on toggle. my code is written below.
REP
<div class="comment-reply" style="display: None;">
{% for child_comment in comment.children%}
{{ child_comment.timestamp|timesince }
{% endfor %}
</div>
<script type="text/javascript">
$(document).ready(function(){
$(".comment-reply-btn").click(function(event){
event.preventDefault();
$(this).parent().next("comment-reply").fadeToggle();
})
})
</script>
You're navigating to the wrong DOM element. next() finds the next matching sibling, but you've put parent() first - so you are looking for the next sibling of that parent. Drop that parent call.
$(this).next("comment-reply").fadeToggle();

jquery toggle in a for loop using Jinga2 template

I am trying to hide/show a div that is within a for loop using jquery's toggle. When I click the button to toggle, the div slides out for a quick moment, but then hides again. When this happens, the toggle button almost seems disabled for the next click...then works again with the same problematic div display. I used the {{email.sender}} template value because when I clicked on the toggle button, all the items in the list would be activated instead of just that one. The below code is inserted into a tab with Jquery (this part is working). Thanks for any advice you can give on this-
<div id="email_received_list">
{% for email in email_received_list %}
<p>
<input type="button" id="{{email.sender}}" value="Show Message"> {{email.sender}}: {{ email.subject }}
</p>
<script>
$(document).ready(function(){
$('#{{email.sender}}').click(function() {
$('.{{email.sender}}').slideToggle('fast');
return false;
});
});
</script>
<div class="{{email.sender}}" style="display:none; background-color:#4CF;width:100%;height:100%;"></div>
{% else %}
(You have not received any messages yet.)
{% endfor %}
Ok, I feel stupid on this one - but once I added some actual content to the div (not just trying to color a square) it worked fine. I guess since it was in a loop, it was trying to size the div match the content. When there was no content, the div just hid itself again. If you know something different on this, please let me know -thanks.

Why is this "this + sibling" call failing?

I am having some trouble with what I thought should be a simple sibling selector in jQuery.
The problem generates no error message, of course, it simply fails to select properly. Inside a document(ready) function() I have the following simple code to first hide all of the popups, then wait for a person to click an image which will show the sibling pop-up:
//hide all the charm pop ups
$(".charm_pop").hide();
$(".charm > img").click(function() {
$("this + .charm_pop").show();
})
My HTML is being generated by a Django for loop, so there will be many iterations of this simple image/popup combo markup:
{% for ch in charms %}
<div class="charm">
<img src="{{ MEDIA_URL }}images/charms/{{ ch.image }}" alt="{{ ch.name }}" />
<div class="charm_pop">
<p id="charm_name">{{ ch.name }}</p>
<p id="charm_desc">{{ ch.description }}</p>
<p id="charm_price">${{ ch.price }}</p>
<form method="post" action="." class="cart">{% csrf_token %}
<p>**some inputs and what not</p>
</form>
</div>
</div>
{% endfor %}
As you can see, I simply wait for an image to be clicked, and when it is I select it's sibling and reveal that corresponding pop-up. Yet when I click an image, nothing happens. If I replace $("this + .charm_pop").show(); with $(".charm_pop").show(); it does indeed show all of the pop-ups, so the click function is working, the selector is just wonky.
Am I misunderstanding how this is working in this context?
When writing jQuery selectors the string "this" simply means "an HTML element <this>", so $("this + .charm_pop") will certainly not work.
Concatenating the string representation of an object with something else is also not meaningful here, so $(this + " .charm_pop") will also not work.
You should be using appropriate traversal functions instead, starting from $(this):
$(this).next(".charm_pop").show();
There is a number of different ways to go from the clicked image to its sibling .charm_pop, but .next() is fastest and also semantically identical to the adjacent-sibling selector + that you are trying to utilize.
Your code is basically using the + css selector
$("this + .charm_pop").show();
element+.class which says "Selects all the .class elements that are placed immediately after element
In your case it is looking for an element named this. I doubt you have any elements with the tag name of <this>.
Your code needs to be
$(this).siblings(".charm_pop").show();
or
$(this).next(".charm_pop").show();
You can do this :
$(this).find(".charm_pop").show();

How to pass parameter dynamically to JQuery click event from HTML elements?

First of all, I have to mention that I am a newbie in the JavaScript and JQuery world. I am not sure if I put down an appropriate title for my question but I'll try my best to explain my problem.
Scenario: I have a list of items whose names are being displayed. When one of the items is being clicked, a popup should show up and display the description of the item. The description is retrieved from the server via an AJAX call upon the click. The AJAX call requires the unique id of the item (in the database) to be provided. Here comes my problem which has two parts:
I don't know how and where to include the item id in the HTML. Note that the list only displays item name not id.
Assume 1) is resolved, how can I pass the id of the item that's being clicked to the AJAX call.
This is the HTML of the list of items. As you can see, it illustrates part 1) of my problem (ie. don't know how to include the ids in the HTML).
<ul>
<li class="item">Item1</li> <!-- this item has id=1 in the database -->
<li class="item">Item2</li> <!-- this item has id=2 in the database -->
<li class="item">Item3</li> <!-- this item has id=3 in the database -->
</ul>
Below is the JQuery click event handler that sends the AJAX call (ie. getJSON) to the server. Note that the part 2) of the problem is illustrated by the line var item_id = ??. Note that popup is a self-defined javascript.
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$(".item").click(function() {
var item_id = ??
var data = {"item_id":item_id};
$.getJSON("/item/json", data, function(data) {
var name = data[0]["fields"]["name"]
var description = data[0]["fields"]["description"]
popup.call(this, name, description);
});
});
});
</script>
Additional Info: For the server side I use Django 1.3, and JQuery 1.5.2 for the client side.
I hope I have made my question clear and I appreciate any help from you experts. Thanks.
Here is an example that is similar to what I am looking for.
http://esdi.excelsystems.com/iseries400apps/exmain.pgm?wsname=DIALOG.pgm&wsnumb=214&wsprogtype=P
http://www.w3schools.com/tags/tag_li.asp
The < li > tag supports the following standard attributes:
id Specifies a unique id for an element
In this case use:
<ul>
<li class="item" id="item_1">Item1</li> <!-- this item has id=1 in the database -->
<li class="item" id="item_2">Item2</li> <!-- this item has id=2 in the database -->
<li class="item" id="item_3">Item3</li> <!-- this item has id=3 in the database -->
</ul>
And
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$(".item").click(function() {
var item_id = $(this).attr('id').replace('item_','');
var data = {"item_id":item_id};
$.getJSON("/item/json", data, function(data) {
var name = data[0]["fields"]["name"]
var description = data[0]["fields"]["description"]
popup.call(this, name, description);
});
});
});
</script>
Javascript (and jQuery in particular) are used for client-side scripting. As such, you will need to supply the data within the HTML document. You can use jQuery' Metadata plug-in to supply the item ID:
<li class="item" data="{ItemID: 'Your_Item_ID'}">Item1</li>
and retrieve it via:
var item_id_structure = $(this).metadata().ItemID;
If your item names are unique, then send the item names via Ajax.That way you can avoid Item ID's.
HTML5 natively supports data attributes that can be easily accessed with jquery
http://api.jquery.com/data/#data-html5
For example, given the following HTML:
<div data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"John"}'></div>
1
All of the following jQuery code will work.
$( "div" ).data( "role" ) === "page";
$( "div" ).data( "lastValue" ) === 43;
$( "div" ).data( "hidden" ) === true;
$( "div" ).data( "options" ).name === "John";

Categories

Resources