javascript : changing <DIV> onclick value - javascript

I have a <DIV> which I'm using as a button like this :
<div id='project_1_task_2_is_done'
class='button_style_1_small' onClick='taskIsDone(1,2,"y");'>
Is done?
</div>
I want to change the onClick string value to taskIsDone(1,2,"n") once the user clicks on it, and then, when it clicks again, back to taskIsDone(1,2,"y") and so on.
I'm trying to accomplish this from the taskIsDone javascript function such as
if(is_done=='n'){
document.getElementById('project_' + project_id + '_task_' + task_id + '_is_done')
.onclick = "taskIsDone(" + project_id + "," + task_id + ",'y');"
}
but it's not working.
I looked over the net to more than 7-8 examples, most from here (Stackoverflow) but I'm not finding the answer to my question (which is basically changing dynamically the onclick string for that DIV id. I don't want to run a function, as most of the examples i found present, just want to change the onclick string value, modifying "y" to "n", and again "y", etc, for each click on the div button.
thanks!!

See http://jsfiddle.net/wnw0oskd/
You can change it as an attribute, as the alert shows onlick of the element is not 'taskIsDone(1,2,"y");' but a function.
document.getElementById('project_' + project_id + '_task_' + task_id + '_is_done').setAttribute("onclick", "taskIsDone(" + project_id + "," + task_id + ",'n'");"

If you print the current value of document.getElementById('your_div').onclick you realize tht it's not the string taskIsDone(1,2,"y");, but it's:
function (event) {
taskIsDone(1,2,"y");
}
So, if you want to change the value of .onclick, assign it one such a function.
Example (toggle the value of .onclick between a() and b()):
<html>
<body>
<script>
function a() {
alert("a()");
document.getElementById('foo').onclick = function(event) {
b();
}
}
function b() {
alert("b()");
document.getElementById('foo').onclick = function(event) {
a();
}
}
</script>
<div id="foo" style="position: absolute; left: 20px; top: 20px; width: 200px; height: 50px; background-color: red;" onclick="a();">
</div>
</body>
</html>

to answer your question specifically, try setting "onlick" to a function instead of a string:
if (is_done=='n'){
var elmt = document.getElementById(...); // arguments omitted for brevity
elmt.onclick = function(project_id, task_id) {
taskIsDone(project_id, task_id, 'y');
}
}
Having said that, though, there are better ways of doing this sort of thing. You could, for instance keep your state in a data attribute attached to the div:
<div id='project_1_task_2_is_done' data-done="no"
class='button_style_1_small' onClick='toggleDone(ev, 1, 2)'>
Is done?
</div>
<script type="text/javascript">
function toggleDone(ev, projectId, taskId) {
var elmt = ev.target
elmt.dataset.done = elmt.dataset.done == "yes" ? "no" : "yes"
}
</script>
See http://www.w3schools.com/tags/att_global_data.asp

Try this.
<div id='project_1_task_2_is_done'
class='button_style_1_small' >
Is done?
</div>
var check=false;
var button = document.getElementsByClassName('button_style_1_small');
button.click =function(){
if(check==false){
check=true;
taskIsDone(1,2,"n");
}else{
check=false;
taskIsDone(1,2,"y");
}
}

Related

Get value from one class and add text to all with the same name?

I may have two or more classes with the same name.
After user click in one button, I would like to count + 1 to a counter that I have. So I tried:
var likes_count = parseInt($('.likes_count'+I).first().text()) + 1;
$('.likes_count'+I).first().text(likes_count);
with first, it will change only the first elemente value after click, adding +1 on it, but the second and so one will not change. If I remove first the counter will go crazy.
How to change all of them? adding +1 on classes with the same name?
I commented the code explaining my approach, hope it helps
$('button').click(function(){
//get class index by splitting on 'likes_count'
var classIndex = $(this).attr('class').split('likes_count')[1];
var likes_count = parseInt($('.likes_count'+classIndex).first().text()) + 1;
//you were close, just apply pass function to each .text() like so:
$('.likes_count'+classIndex).text(function(){
return likes_count;
});
});
.likes_count1{
background: red
}
.likes_count2{
background: green
}
.likes_count3{
background: blue
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="likes_count1">0</button>
<button class="likes_count1">0</button>
<button class="likes_count2">0</button>
<button class="likes_count3">0</button>
<button class="likes_count3">0</button>
<button class="likes_count2">0</button>
<button class="likes_count2">0</button>
You can use :
$(".likes_count").each(function() {
$(this).text(parseInt($(this).text()) + 1);
});
Example :
$(document).ready(function() {
$("button").on("click", function() {
$(".likes_count").each(function() {
$(this).text(parseInt($(this).text()) + 1);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="likes_count">3</div>
<div class="likes_count">5</div>
<div class="likes_count">7</div>
<button type="button">Increment</button>

Variable Interpolation in Jquery code inside for loop

I have some code, http://jsfiddle.net/hucw940s/
which has a for loop.
before
<div id="container">
</div>
after
for (i = 1; i < 4; i++){
var showMe = $('<a href=# id="link' + i + '">')
.append('click').click(function(){ alert('You clicked num: ' + i) });
$('#container').append(
$('<div id="div'+i+'">').append('this is div number: ' + i).append(showMe)
);
}
so the links are generated with id=link1, link2, link3 etc, and the divs appended are the same, however the onclick code seems to put the var i in after the event, so on clicking any link they say "you clicked number 4"
How can I make this use the i from the clicked link inside the function that is called on click?
What you are experiencing is the expected behavior based on your code.
However, what you are actually trying to do is pass in event data to your click function. This can be accomplished like this:
for (i = 1; i < 4; i++) {
var showMe = $('<a href=# id="link' + i + '">').append('click')
.click({value: i}, function (e) { alert('You clicked num: ' + e.data.value) });
$('#container').append($('<div id="div' + i + '">').append('this is div number: ' + i).append(showMe));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="container">
</div>
First, you have to assign the event data, so we pass in an object
{value: i} before we pass in the handler function.
Then, in the handler function, we assign the variable e to the
event, so we can access the data attribute.
Finally, you access the value that was passed in by referencing
e.data.value.
You can add as many event data objects as you want and reference them by name this way.
The reason your code is not working as you are expecting is because the variable i is already equal to 3 by the time the click event happens, since the for loop completes before you are able to click any of the links.
Hope this helps give you a better understanding of why your code is behaving the way it is and what you can do to fix it.
Store the id in a data-attribute.
Updated jsFiddle

Two different css classes in the same javascript line

I'm trying to assign these css values (below) for the javascript line in the example below, but don't know a way to target valueB with the .valueB-class.
$(".valueA").html(valueA + " valueB" + ((valueA > 1) ? 's': ''));
.valueA-class { font-size:X }
.valueB-class { font-size:XX }
Here is an example of what I need help with (you may have to click on the input boxes in the results panel to get the calculations to show up - that's what I had to do): http://jsfiddle.net/hughett/g21g8t85/
Welcome to stackoverflow!
Your question seems a bit vague. I assume that this is you want to achieve. In the specific example the value of the class is changed through the use of the jquery attr function. Firstly, the specific div in which our text is placed is retrieved and then the value gets specified. I am attaching a code snippet below.
A general note, using a . in css indicates that you are referring to a class so there is no need to attach a -class in the name.
$( "#myButton" ).on( "click", function() {
var attr = $("#myText").attr('class');
console.log(attr);
if (attr == "valueA") {
$("#myText").attr("class","valueB");
} else {
$("#myText").attr("class","valueA");
}
});
.valueA { font-size:11pt }
.valueB { font-size:25pt }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="myButton" type="button">Change Text size</button>
<div id="myText" class="valueA">sdsa asd aasdaas asdjlasj dasdkas asldjsalj slad TEST</div>
EDIT to include another answer
In order for the text included in a single span to have different font-size you need to separate it somehow. In the specific example, I have added a second span in the respective div and adjusted the cacl_summary method to get the expected result.
The code is available below; I have also updated the jsfiddle here
<div style="background:yellow;"><span class="label">Simple payback</span>
<span class="figure sp"></span> <span class="figure year"></span></div>
function calc_summary(){
if (cspy) {
sp = parseFloat($("input[name=upgrade]").val()) / cspy;
if (sp) {
sp = (sp < 100) ? sp.toString().substring(0, 4) : sp;
$(".sp").html(sp);
$(".year").html(" years" + ((sp > 1) ? 's': ''));
$(".ror").html(parseInt((1/sp) * 100) + '%');
}
}
}

jQuery: add multiple data attributes with each click function

I have a click function setup whereby when you click on the .click div, it takes the data-hook attribute, and add it as a data-filter attribute to the .button div, this works fine, but after each click it is replacing the data-filter attribute with the new one, ideally I want to add a new value to the attribute with each click, separating each value with a comma.
Here's a jsFiddle demo: http://jsfiddle.net/neal_fletcher/pSZ2G/
HTML
<div class="button">THIS</div>
<div class="click" data-hook="one">CLICK</div>
<div class="click" data-hook="two">CLICK</div>
<div class="click" data-hook="three">CLICK</div>
<div class="click" data-hook="four">CLICK</div>
<div class="click" data-hook="five">CLICK</div>
jQuery:
$(".click").click(function () {
var thing = $(this).attr("data-hook");
$('.button').attr('data-filter', thing);
});
If this is at all possible? Any suggestions would be greatly appreciated!
You can store the previous value and can concatinate with new clicked value, something like.
$(".click").click(function () {
var thing = $(this).attr("data-hook");
var earData = $('.button').attr('data-filter');
if(typeof earData != 'undefined'){
$('.button').attr('data-filter', earData + ","+thing);
}else{
$('.button').attr('data-filter', thing);
}
});
DEMO
$(".click").click(function () {
var thing = $(this).attr("data-hook");
var prevValue = $('.button').attr('data-filter');
if(prevValue){
$('.button').attr('data-filter', prevValue +','+thing)
}
else{
$('.button').attr('data-filter', thing)
}
});
$(".click").click(function () {
var thing = $(this).attr("data-hook")||'';
var df = $('.button').attr('data-filter')||'';
$('.button').attr('data-filter', df+','+thing)
});
on a side note.. I hope you don't have any other elements with a .button class in it.. if you're looking to update a single target, you should reference by an id attrib instead.

Jquery binding events

Why does the handler bound to an event of an element fire the wrong result? I would expect the click event of Div1 below to popup a dialog stating 'div1' but it popup's 'div2'.
I am new to this and I am scratching my head to work out why this is happening. I would appreciate any help to explain.
Cheers,
Alex
<!DOCTYPE html>
<html>
<head>
<title>TestEvents</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
//Object Array
var objToTest = [{ TabName: "div1" },
{ TabName: "div2"}];
//Adds events to each div
function TestWhatIsGoingOn(myObjToTest) {
for (i in myObjToTest) {
$('#' + myObjToTest[i].TabName).click(function() { TestResult('TabName: ' + myObjToTest[i].TabName); });
}
}
function TestResult(message){
alert(message);
}
$(document).ready(function() {
TestWhatIsGoingOn(objToTest);
});
</script>
<style type="text/css">
#div1, #div2
{
border: solid thin black;
height: 100px;
width: 300px;
}
</style>
</head>
<body>
<div id='div1'>div1; click here to show expected result: 'TabName: div1'</div>
<div id='div2'>div2; click here to show expected result: 'TabName: div2'</div>
</body>
</html>
it seems a classic closure problem, because when you click on div (any) i variable has already reach the end of for loop (so it always prints the last value). Try to change like so
function TestWhatIsGoingOn(myObjToTest) {
for (i in myObjToTest) {
(function(i) {
$('#' + myObjToTest[i].TabName).click(function() { TestResult('TabName: ' + myObjToTest[i].TabName); });
)(i);
}
}
Your problem is in this section of code:
for (i in myObjToTest) {
$('#' + myObjToTest[i].TabName).click(function() {
TestResult('TabName: ' + myObjToTest[i].TabName);
});
}
The trouble is that the value of i is not hard-coded into this section. When the function runs, it will see what the current value of i is. Since you have since incremented it to refer to your second tab, this function will always refer to the second tab. This feature of Javascript is called a closure -- it closes in the value of i.
The easiest way around this is to use jQuery to bind to more than one object at once, and then evaluate based on the object clicked on:
$(document).ready(function(){
$('div').click(function(){
alert('TabName: ' + this.id);
});
});
This will do everything you want your code in the question to do.
In a real-world situation, you would probably need to give the divs a common class (e.g. toClick) and then use a jQuery class selector ($('.toClick')).

Categories