Just don't know why this piece of code is not working: (onClick not working, click() is working (using console))
function click(ID)
{
if(cost[ID] <= currency[costID[ID]])
{
currency[costID[ID]] -= cost[ID];
currency[ID] += buyamout[ID];
document.getElementById(x[costID[ID]]).innerHTML = "<center>"+(Math.round(notyfication(currency[costID[ID]])*100)/100)+not+"</center>";
document.getElementById(x[gainID[ID]]).innerHTML = "<center>"+(Math.round(notyfication(currency[gainID[ID]])*100)/100)+not+"</center>";
}
}
...'<button onClick="click('+i+');">'+button+x[i]+'</button>'
this gives output <button onClick="click(0);">Make DNA</button>
and after clicking button nothing happens.
There could be a namespace conflict with your click. Use another name like button_click below
var i = 0;
var button = "Make ";
var x = [['DNA']]
document.writeln('<button onclick="button_click('+i+');" >'+(button+x[i])+'</button>');
function button_click(ID) { // notice the function name change
alert(ID);
}
Code below not working:
var i = 0;
var button = "Make ";
var x = [['DNA']]
document.writeln('<button onclick="click('+i+');" >'+(button+x[i])+'</button>');
function click(ID) { // the function name click may have been used already
alert(ID);
}
indeed onclick="click('+i+');" executes the javaScript code between the double brackets: click('+i+');: it calls the javaScript click() function, but this does not work if you declare function click() and someone else did that elsewhere in javaScript code.
if onClick is not working you can also use addEventListener will do the same job.
for e.g.
element.addEventListener('click', function() { /* do stuff here*/ }, false);
To answer your question you must do the following.
Change:
onClick="click(0)"
To:
onclick="click(0)"
That will most probably fix your problem.
Related
Let's say I have several textareas, and I want to add event listener to each textarea. When I type inside a textarea, I need to console the value typed inside it. I just can't figure out how to refer "this" to each textarea called in looping when being added event listener. The code below results in "undefined" in the browser console. Maybe you can set it right. Appricated the help. Thank you very much.
window.addEventListener("load", function(){
var char_max_inputs = document.querySelectorAll('.char_max');
for (var i = 0; i < char_max_inputs.length; i++){
var max_char = char_max_inputs[i].getAttribute("max_char");
var counter_id = char_max_inputs[i].getAttribute("counter_id");
char_max_inputs[i].addEventListener("keyup", function(){count_char(counter_id, max_char);}, false);
}
});
function count_char(counter_id, max_char) {
console.log(this.value);
}
You can solve it like this by using Function.prototype.bind
window.addEventListener("load", function() {
var char_max_inputs = document.querySelectorAll('.char_max');
for (var i = 0; i < char_max_inputs.length; i++) {
var max_char = char_max_inputs[i].getAttribute("max_char");
var counter_id = char_max_inputs[i].getAttribute("counter_id");
char_max_inputs[i].addEventListener("keyup", count_char.bind(char_max_inputs[i], counter_id, max_char), false);
}
});
function count_char(counter_id, max_char) {
console.log(this.value);
}
<textarea class="char_max"></textarea>
<textarea class="char_max"></textarea>
<textarea class="char_max"></textarea>
this can be very confusing in JavaScript, if not read about properly. An excellent resource to understand it is here
UPDATE
As pointed out in the comments, the example using call and bind together was incomplete. Removing it.
The input named alternativa-*** will have the *** changed in the PHP that comes before. I'm not using a form on PHP only a onClick statement calling the respondeQuestao function. But this code seems to not work. Someone have any suggestion.
$(document).ready(function() {
function respondeQuestao(qid,resposta) {
var alternativa = document.getElementsByName('input[name = "aternativa-"' + qid ']:checked').value;
document.getElementById("demo").innerHTML = 5 + 6;
if(alternativa==resposta) {
$("#botao-questao"+qid).hide();
};
if(alternativa!=resposta) {
};
};
})
Defining a function within the jQuery Ready statement limits the accessibility - define it outside of the jQuery Ready statement but call it when you need it.
function respondeQuestao(qid, resposta) {
var alternativa = $("INPUT[name^='alternativa-']:checked").val();
$("#demo").html(5+6);
if (alternativa == resposta) {
$("#botao-questro" + qid).hide()
} else {
//
}
}
Call the function inside jQuery:
$(function() {
respondeQuestao("id", 11);
});
I hope this helps.
I am new to Javascript and also new to this Website.
I have about 40 Buttons which are all in the class "foo".
I also have a Javascript function named "run".
How can I set the Javascript to run whenever one of the buttons in class "foo" is pressed without actually setting the button to run it?
Is this even Possible?
Yes. Here is an example using jQuery.
$('.foo').click(function() {
run();
});
OR, using plain old JavaScript (see the jsfiddle):
//generates a "NodeList" of all buttons
var foo = document.getElementsByTagName('button'),
//then, we turn it into an actual array
foo = Array.prototype.slice.call(foo);
foo.forEach(function(button) {
//check to see if that button has the class "foo"
if(button.classList.contains('foo')) {
button.onclick = function() {
return run();
};
}
});
function run() {
console.log('run');
}
You could use
getElementsByClassName
but the downside of that, is that the only version of IE in which it is supported is 9+ (including all other major browsers), which is fine, if that's what you decide to go with.
Live Demo
You can copy + paste this right into your code and should work perfectly.
var buttons = document.getElementsByClassName('foo');
for (var i = 0; i < buttons.length; i++) {
addEvent(buttons[i], 'click', run);
}
function addEvent(element, myEvent, fnc) {
return ((element.attachEvent) ? element.attachEvent('on' + myEvent, fnc) : element.addEventListener(myEvent, fnc, false));
};
Without jQuery:
var foos = document.getElementsByClassName('foo');
for (var i=0; i<foos.length; i++) {
foos[i].onclick = function() { run() };
}
JSFiddle: http://jsfiddle.net/8AKeP/
There are 3 simple ways to accomplish this.
First, you can just use plain vanilla Javascript. No external libraries are required.
// Get all buttons
var buttons = document.getElementsByClassName('foo');
// Loop through the buttons
for(var i = 0; i < buttons.length; i++){
// Tell each button that when it is clicked, call the "run" function.
buttons[i].onclick = run;
}
Second, You can specify the onclick methods in your HTML. This is a bad approach as it forces you to define global methods (functions that are accessible from anywhere), and also ties your code with your markup, making it hard to change one without changing the other.
<!-- Old HTML -->
<button class="foo">Text</button>
<!-- New HTML -->
<button class="foo" onclick="run()">Text</button>
Lastly, You can include the very helpful jQuery library to handle it for you. jQuery provides an easy way to handle binding events, selecting elements, etc.:
// One line (deconstruction below)
// $(".foo") => Find me all elements with a class name of "foo"
// .on("click", => When those elements are clicked
// run); => Call the "run" method.
$(".foo").on("click", run);
The last approach, using jQuery has become the sort of de facto standard way of doing this.
Try this:
var run = function(){
//your function goes here
}
$(document).on('click', '.foo', run);
I would use jQuery, for example:
$('.foo').click(function(){
run();
});
it is simpler to program. However, without using jQuery:
var buttons = document.getElementsByClassName('foo');
function run(){
alert('hi');
}
for(var i = 0; i < elements.length; i++){
buttons[i].onclick = function() { run() };
}
The script below adds items to an array when you click the link, and generates a list of items as html output. You can see an example here: http://jsfiddle.net/dqFpr/
I am trying to create a function to delete items from the list. Not a difficult task with splice(), but somehow clicking the delete link doesn't trigger the test_function() function.
Can someone tell me what I am doing wrong, or show me another way of triggering the function? Your help is really appreciated ;-)
<script language="javascript">
$(document).ready(function() {
function test_function( number ) {
/* This function is not triggered, nothing works inside here!! */
}
});
var lines = [];
function update_list( lines ) {
var thecode = '';
for(var i = 0; i < lines.length; i++) {
thecode = thecode + lines[i] + ' <a onclick="javascript:test_function('+i+')" href="#">(delete)</a><br />';
}
$('div#display').html(thecode);
}
$('a#new').click(function() {
lines.push('another line');
update_list(lines);
});
</script>
<div id="display"></div>
Add a new line
Because in the text assigned to display's innerHTML, *test_function* is just plain text that is evaluated by the HTML parser. At that point, its scope is global, not within the IIFE passed to $(document).ready(). You can fix that by making the function global:
$(document).ready(function(){
window.test_function = function (number) {
// do stuff
}
....
});
or
var test_function;
$(document).ready(function(){
test_function = function (number) {
// do stuff
}
....
});
Or whatever method you like to get access to the function. But while it is declared inside an anonymous function's scope, you can only get access to it from a function that has a closure to the variables in that scope.
I am a beginner in javascript, can you tell me what's wrong with the below code?
I want this to invoke buttonPressed() when a button gets pressed. From buttonPressed() it should call changeColor1(), changeColor1() should change the text color of a paragraph, and start a timer to invoke changeColor2(). Similarly changeColor2() should also change the color and call changeColor1() once the timer expires.
<html>
<head>
<script type="text/javascript">
function changeColor2()
{
alert("2");
var v = document.getElementById("onet");
v.style.color = rgb(0,255,255); // this statement is not working
var t=setTimeout(changeColor1,3000);
}
function changeColor1()
{
alert("1");
var v = document.getElementById("onet");
v.style.color = rgb(255,255,0); // this statement is not working
var t=setTimeout(changeColor2,3000);
}
function buttonPressed()
{
alert("Hello");
changeColor1();
}
</script>
</head>
<body>
<p id="onet"> Hello how are you? </p>
<form>
<input type="button" value="Display alert box!" onClick="buttonPressed()" />
</form>
</body>
</html>
Do not invoke the function, pass the reference only:
var t=setTimeout(changeColor2,3000);
I think you want style.color not .color.
By the way... please tell us what the code is supposed to actually do and what is wrong initially.
You need to quote style property values-
v.style.color = 'rgb(255,255,0)';
1) I don't like the fact that you have two timeouts set. Just call one function and use a flag to toggle between the two options.
2) The parameter to setTimeout that you want to use is a function pointer (changeColor) not the result of a function call (changeColor())
var flag = false;
var t;
function changeColor()
{
var v = document.getElementById("onet");
if(flag){
v.color = rgb(255,255,0);
} else {
v.color = rgb(0,255,255);
}
flag = !flag;
}
function buttonPressed()
{
alert("Hello");
t=setInterval(changeColor,3000);
}
Not really knowing what it is you're trying to do, I can tell you that your button's onClick handler references a method name that isn't in your code. Judging by the names of your methods, I think you meant to put "buttonClicked" in there.
Nevermind, looks like you changed it while I was typing.
Instead of v.color = rgb(0,255,255); use v.style.color = "#0ff".