Reputation: 1249
HI i have a dynamic li in my django template
<script type="text/javascript" language="javascript">
function setSize(size) {
document.getElementById('id_option1').value = size;
}
function notavailable(notavai) {
alert('selected product is not available');
}
</script>
{% for i in prosize %}
{% if i.num_in_stock > 0 %}
<li><a id="{{i.option1}}1" ref="javascript:setSize('{{i.option1}}')">{{i.option1}}</a></li>
{% endif %}
{% endfor %}
i need to add the background *color* to active a link onclick i am already using a javascript function on a .Please suggest how can i do this
Upvotes: 0
Views: 467
Reputation:
So, it's easy, in HTML markup you have:
<a class="order" id="{{i.option1}}" href="javascript:setSize('{{i.option1}}')">{{i.option1}}</a>
id
. I deleted the 1
from at the end of it.href
attribute you wrote, was invalid. I've correct it.And change your setSize
function to this:
// because IE9 (and below) doesn't support for getElementsByClassName
// we use this funciton instead
// written by Jonathan Snook
// http://snook.ca/archives/javascript/your_favourite_1
function getElementsByClassName(node, classname) {
var a = [];
var re = new RegExp('\\b' + classname + '\\b');
var els = node.getElementsByTagName("*");
for(var i=0,j=els.length; i<j; i++)
if(re.test(els[i].className))a.push(els[i]);
return a;
}
function setSize(size) {
// i just comment this line as i don't know what it doesyourself
// document.getElementById('id_option1').value = size;
// change the color the others to transparent
var others = getElementsByClassName(document, 'order');
for (var i = 0, l = others.length; i < l; i++) {
others[i].style.backgroundColor = 'transparent';
}
// this line will change the background color of your element
document.getElementById(size).style.backgroundColor = '#ff6600';
}
If you are using jQuery, there is no need to use javascript internally, let's jQuery handle all them for you.
Write this code in your .js
file:
$(function () {
// get al links and attach the `click` handler to them
$('.order').on('click', function (e) {
// prevent default behaviour of link
e.preventDefault();
// get size and do something with it
var size = $(this).attr('data-size');
$('#textbox').val(size);
// change the color the others to transparent
$('.order').css('background-color', 'transparent');
// change the color of link
$(this).css('background-color', '#ff6600');
});
});
Upvotes: 2
Reputation: 19262
in your loop, you can also bind the on click event and pass the id ...like
{% for i in prosize %}
{% if i.num_in_stock > 0 %}
<li><a id="{{i.option1}}1" onclick='ChangeColor('+{{i.option1}}1+')' ref="javascript:setSize('{{i.option1}}')">{{i.option1}}</a></li>
{% endif %}
{% endfor %}
function ChangeColor(id)
{
$("#"+id).css("background","#fff");
}
Upvotes: 0
Reputation: 885
What you want should not be implemented in javascript or python but CSS. You should use :active
selector in CSS.
http://www.w3schools.com/cssref/sel_active.asp
Upvotes: 0