Django- Jquery loops through all options - javascript

Im doing server side rendering with the help of Django. In my django templates Im looping through all the values obtained from my Database. In jquery while selecting a single value, JS gives me all the values obtained from database, but I wanted only selected values
Views.py
def theme(request):
context={}
context['All']=Theme.objects.all().count()
for t in ThemeCategory.objects.all():
context[t.categoryName]= t.theme_set.count()
context=collections.OrderedDict(sorted(context.items()))
return render(request,'theme-list.html',{'category_name':context})
In templates
<ul class="pick-tags" >
{% for category_name,count in category_name.items %}
<li id="item_cat">
<span id="item_cat_name">{{ category_name }}</span>
</li>
{% endfor %}
</ul>
In jquery Im selecting the required value
$('li#item_cat').on('click', function () {
alert($('span#item_cat_name').text())
})
But instead of giving me a single value, It me all the value obtained from DB.
How should I get only one value when click on <li>
Any help in obtaining selected value would be helpful

First of all, id of each HTML element should be unique. And you are creating multiple li and span elements with the same id. Make sure it's unique to prevent undesired bugs. it's better to use class and data attributes if needed.
Second, you need to get text of selected element, not any element, so you need to use this:
$(this).find('span').text()

In your template, you're giving every <span> element the same identifier (item_cat_name). Your second jQuery selector selects all <span> elements with that identifier.
To resolve this, change your jQuery to something like:
$('li').on('click', function () {
alert($(this).children('span').text())
});
This would only show the texts of <span> elements directly below the clicked <li> element (using $(this) is the key here).
Also, I would advise to give every <span> element an unique identifier, e.g. the primary key of the ThemeCategory; so that you can then base your further actions on that.

Related

How to store the element inside anchor tag in a variable?

I am using table and the element inside the table are added dynamically with the JSON data. The table data consists of Id and other things. I had put id inside the anchor tag so that it gets navigated to another page which shows all the data of that Id. I want to show the data of only selected Id. So I want to set the element inside the anchor tag to a variable ... is there any way to achieve this ?
<a href="other_page.html">link Label<a>
Now I want to store this "link Label" into a variable in JavaScript or AngularJS is there any way?
You can use data attribute for this. for example
<a href="other_page.html" data-id="3" id="click">link Label<a>
and in you javascript :
<scrtipt>
document.getElementById("click").addEventListener("click", function(event){
alert(this.getAttribute("data-id"));
});
</script>
Hope it can be helpful.
<a id="jsonObject.id" href="other_page.html" onClick="clickFunction">link label</a>
You can set anchor id with that particular id. Then on click function you can send event object and get that particular ID.
JS code
function clickFunction(event){
console.log(event.currentTarget.id);
}
Sure you can do!
You can get the text inside tags by calling .innerHTML of the element. In your case this would mean something like this:
<a href="other_page.html" id="tagid">link Label<a>
You need an id for the tag and then in JavaScript
var value = document.getElementById("tagid").innerHTML;

How to set a JavaScript variable in attribute of a HTML tag

I know questions with similar titles have been asked before and I seen the answers.
I have a ul element in HTMl:
<ul class="collection with-header"></ul>
In this element li elements are added dynamically through JavaScript:
$('.collection').append('<li class="collection-item">'+'Hello'+'</li>');
Now,for each li element,I want to add a number to it's class attribute to identify every li element uniquely so that I can assign different id attributes to them.For that I wrote:
var j = 1;
$('.collection').append('<li class="collection-item"'+j+'>'+ 'Hello'+'</li>');
$('.collection-item'+j).attr("id",list[i].username);
j++;
When I try to fetch id of li elements by hover event:
$('.collection-item').hover(
function(){
var idd = $(this).attr('id');
console.log(idd);
}
);
Undefined is printed in the console.
What is wrong in this implementation?
EDIT:
The value of list[i].username is working fine,it's value is coming from another file and it's not causing any trouble.
As far as I can see, your placement of i within that string results in i being outside the html className attribute, infact not inside any html attribute at all. Your code:
$('.collection').append('<li class="collection-item"'+j+'>'+ 'Hello'+'</li>');
would result in this final markup:
<li class = "collection-item"0>Hello</li>
<li class = "collection-item"1>Hello</li>
The zero has no HTML signficance and is out of place.
#sphinx's comment is the correct answer, but it is "not being fired" because his code results in each list item having a unique class name with its number at the end like so:
<li class = ".collection-item0">Hello</li>
<li class = ".collection-item1">Hello</li>
when you add the on hover action, you select these elements by the class ".collection-item", not a unique class.
Your solution would look like this:
$('.collection').append('<li class="collection-item '+j+'">'+ 'Hello'+'</li>');
$('.collection-item.'+j).attr("id",list[i].username);
and with this, in your final markup, each list item will have two classes - a shared "collection-item" class, and a numerical value like so:
<li class="collection-item 0"></li>
<li class="collection-item 1"></li>
now you can select each list item (in this example list item 4) by two classes with the selector $(".collection-item.4") as well as apply an action to all collection items with the selector $(".collection-item").
I find this code somewhat ugly looking and I'm not sure if I would be happy with it myself in terms of structure if it were mine, but here is a jsfiddle as a proof of concept :
https://jsfiddle.net/0wqeouxo/ (click on each list item and it will alert its id)
I think you could get more mileage out of jquery's functionality in that loop rather than defining classes inline.
Use this instead
var j = 1;
$('.collection').append('<li class="collection-item'+j+'">'+ 'Hello'+'</li>');
$('.collection-item'+j).attr("id",list[i].username);
j++;
There is a syntax error in your code, please use the above code.
For hover to work, do this
$('.collection-item'+j).hover(
function(){
var idd = $(this).attr('id');
console.log(idd);
}
);
As jQuery operates asynchronously, when you try to set the id, the element is might not be in the dom yet. You could set the id before appending the element, for example:
$('<li class="collection-item '+j+'">'+ 'Hello'+'</li>')
.attr("id",list[i].username)
.appendTo('.collection');
It a dynamically append element .so you could use on().and change the selector like this .[class^="collection-item"] It will match same class name element contain with some other name in the class
$(document).on('hover' ,'li[class^="collection-item"]',function(){
var idd = $(this).attr('id');
console.log(idd);
});

List item value is always 0 using jQuery

Working a page of buttons which populates a textarea with the value of the buttons.
This works fine for items that are buttons, but cannot get it working for list items.
I have to use a list item since some buttons have a drop down.
jsfiddle shows the list item alerting 0 even thought it does have a value.
http://jsfiddle.net/hsw32zv8/
<li class='item_value' value='value'>
<a href='#'>Click</a>
</li>
<br><br>
<button type='button' class='btn btn-success item_value' value='value2'>Click 2</button>
jQuery:
$(".item_value").on('click',function(){
alert(this.value);
});
value is not a valid attribute for the li element (unless it's in an ol, but that seems unlikely given your issues and the fact the value of the attribute you had was a string not a number), nor does the DOMElement for that tag type have a value property.
Adding non-standard attributes to your markup will render the page invalid and may lead to JS and UI problems. If you want to create a custom attribute, use data-*:
<li class="item_value" data-value="value">
Click
</li>
$('.item_value').on('click', function(){
alert($(this).data('value')); // = 'value'
});
li element doesn't have value attribute. However if you still want to get it use attr method:
$( this ).attr( 'value' );
jsFiddle
A list item <li> haves a value but it only takes numbers (note they should be in an <ol>). You gave a string (at interpreted that as 0) so for example:
<li class='item_value' value='1010'>
Click
</li>
Will show up as a value of 1010. You can get around this by adding a data- attribute instead: data-value="someStringHere"
just modified your this.value to $(this).attr('value').
so the complete code:
$(".item_value").on('click',function(){
alert($(this).attr('value'));
});
hopefully helping

Obtaining Upper level li text

So I currently have a list like so on my page
<li class="head">
<b>Introduction</b>
<ul>
<li class="sub">somethingsomething</li>
</ul>
</li>
This list is being used with sortable, so the user can decide on the order, and I am passing this information to a grails controller for use in application logic. So, I am trying to read it in, and place the text contained in the "head" and "sub" classes in 2 different arrays. However, when I use a jquery selector to obtain the head elements, and obtain the text attribute of the element, it contains the inside list as well.
$('#divname').find("ul > li.head").each(function()
{
var current = $(this);
console.log(current.text());
});
results in Introductionsomethingsomething
Is there any way to only obtain the 'Introduction' text from the list, and ignore the text in the nested <ul> and <li.sub>? Due to it being nested, I am unable to figure out how to use jQuery's :not() selector
You can find the b tag using jquery tagname selector.Like this:
var current = $(this).find('b');
console.log(current.text());
Working Demo
May be this is solution:
<script>
$('#divname').find("ul > li.head").each(function()
{
var current = $(this).find("b");
console.log(current.text());
});
</script>

How to select optgroup

Is there a way to select optgroup?
It seems to be disabled all the time. I have tried searching for javascript solutions but could not find any good ones.
A simple
document.getElementById
should suffice. See the JSFiddle I cooked up for you!
var optGroup = document.getElementById('myOptGroup')
optGroup.innerHTML = "<option value='saab'>Saab</option>"
Unfortunately, there is no way to do this inside the native HTML SELECT element. There's also no way to style options inside of a SELECT element, so you can't just use options and make some of them look like optgroups.
You'll have to come up with a work around using a combination of A and UL elements. Here's a basic one using the below HTML:
<div>
Select
<ul>
<li class = "group">
<a href = "#">
Foods
</a>
</li>
<li class = "choice">
<a href = "#">
Hamburer
</a>
</li>
<li class = "choice">
<a href = "#">
Hotdog
</a>
</li>
</ul>
</div>
Fiddle here
Well you can have an example here: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_optgroup
Its just more like a tag, to tell about the options below. Or just like a caption.
If you want to select multiple ones then you might use jQuery created select. I mean a custom one, or you can use checkboxes and merge them in a list as a select tag.
There is no other way to select two options from one select element. Each select must have one and only one value.
Other way is to add the value to each option, and then seperate them using ,. But there is no option to select optgroup Its just a way to group the options under it or more like a label to them.
I am getting a warning alert that I am missing a point, do you want to click on the optgroup and select a value under it? I think this might be the condition!

Categories