I have a variable named as myVar. Its value changes when you click on the checkbox. When the checkbox is clicked you'll get an alert box showing its value as 1. When you deselect it, it will again show a alert box with value 0. This is correct.
Now I have 2 questions.
When I try to submit the document by clicking on Submit then I get an error as Uncaught ReferenceError: confirm_submit is not defined. Why?
When I put the confirm_submit function out of the ready event I don't get the error but then in that case the second alert box which is inside confirm_submit function shows undefined for myVar. Why? Is the myVar not accessible within confirm_submit function?
Code:
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.treeTable.js"></script>
<script type="text/javascript">
var myVar;
jQuery(document).ready(function() {
$("#myTable2").treeTable({
expandable: true,
clickableNodeNames: true,
initialState: "expanded",
});
document.getElementById('myVar').addEventListener('click', myVar, false);
function myVar() {
if (document.getElementById('myVar').checked === true) {
myVar = 1;
} else {
myVar = 0;
}
alert(myVar);
}.................
some functions....................
function confirm_submit() {
alert(myVar);
if (confirm('Press OK to confirm')) {
document.myform.myVar.value = myVar;
document.myform.submit();
reload_parent_and_close_window();
}
}
and some more functions.....................
});
</script>
</head>
<body>
<form name="myform" id="myform" action="$action" method="post" onsubmit="return false;">
<input type="checkbox" name="myVar" id="myVar" value="myVar">Text here
</form>
Submit
</body>
</html>
You seem to be failing to grasp a few fundamental concepts here, some JavaScript some programming basics.
function myVar() {
...
alert(myVar);
}
What did you expect to happen here? myVar the function and myVar the variable in this scope are the same thing. If you declare a variable and then declare a function with the same name, the function will replace the variable in the stack. Also, there is no block scope in JavaScript. Everything declared in a function is declared first by the compiler, regardless of block. So...
function a() {
var a = 1;
if (1) {
var b = 4;
alert(b);
}
alert(b);
}
Don't assume scoping is the same as Java or C++.
Also, if you want to make something explicitly global, then make it explicit. Try renaming the myVar function to something sensible like "onClick_myVar". Then immediately before where the function is declared, put the function inside a closure and declare your state variable:
(function() { // Closure
var myVar;
function onClick_myVar() {
if ($(this).getattr("checked")) {
myVar = 1;
} else {
myVar = 0;
}
alert(myVar);
}
$('#myVar').click(onClick_myVar);
})();
function myVar() {
if (document.getElementById('myVar').checked === true) {
myVar = 1;
} else {
myVar = 0;
}
alert(myVar);
}
That will only work once. As soon as you enter the function myVar you will replace it's value (function is an object in JS) with either 1 or 0, and it will no longer be a function object, but a number.
the problem is... you have same name for your var and the input element..
document.myform.myVar.value = myVar;
so either change your input element's id to someother variable or change all your myVar name
<input type="checkbox" name="myVar" id="inputId" value="myVar">Text here
document.myform.inputId.value = myVar;
Related
I have this function that alerts the user when their amount of "moonstone" is 10. However, for various reasons, I would like the if statement to be outside the function. When I do this though, the alert doesn't work. Could someone please explain and post a fix for it?
<!DOCTYPE html>
<html>
<img id="game-board" onclick="totalCount()" class="game-board" src="https://pics.clipartpng.com/thumbs/Mars_PNG_Clip_Art-3002.png"></img>
<h2 id="counts">Moonstone:</h2>
<script>
let stone = 0;
function totalCount() {
let newCounts = stone++;
document.getElementById('counts').innerHTML= "Moonstone:"+ newCounts;
}
if (newCounts == 10){
alert('10');
}
</script>
</html>
What does work, but that I don't want to use, is
<DOCTYPE html>
<html>
<img id="game-board" onclick="totalCount()" class="game-board" src="https://pics.clipartpng.com/thumbs/Mars_PNG_Clip_Art-3002.png"></img>
<h2 id="counts">Moonstone:</h2>
<script>
let stone = 0;
function totalCount() {
let newCounts = stone++;
document.getElementById('counts').innerHTML= "Moonstone:"+ newCounts;
if (newCounts == 10){
alert('10');
}
}
</script>
In your code you calling the totalcount() function on onclick event so whatever inside the totalcount() function will executed and code outside the totalcount() function will not execute
I'm not entirely clear why you wouldn't want the if test within the function. But, there is something that you could do:
const counter = {
value: 0,
addOne: function() {
this.value++;
if (this.value > 10) {
alert("Too many");
this.value--;
} else {
document.getElementById("counts").innerHTML = "Moonstones: " + this.value;
}
}
}
function updateCounter() {
counter.addOne();
}
<button onclick="updateCounter();">Add</button>
<div id="counts"></div>
This creates the counter as an object and includes an if test on a addOne function directly attached to that object. Whenever the updateCounter() function is called, the addOne function updates the counter value and checks to see if it has passed 10. If it has, the user gets and alert, otherwise the "counts" element gets updated.
But, as others have said, there is no real reason why an if test shouldn't be part of a function - perhaps you could explain your reasons for that requirement?
<html>
<head>
<script>
function myFunction(){
alert(input);
}
window.onload = function(){
var input = "hello";
myFunction();
}
</script>
</head>
<body>
</body>
</html>
This is my code why it doesn't alert hello?
input is not a global variable in your case, you can't access it through the other function, is scoped to the anonymous function bound to onload event.
If you want to access it like if it's a setting, you must declare it outside of any function OR you must declare it without var OR you must declare it with window.input. In any case, I won't suggest you to use any of the mentioned feature unless the variable is actually something that should be shared across all your application.
The problem is that the input within myFunction refers to a global variable, but the input within the onload is a local variable.
Try passing the input as a parameter to myFunction:
function myFunction(input){
alert(input);
}
window.onload = function(){
var input = "hello";
myFunction(input);
}
Or declare input as a global variable and remove the var from within the event handler:
var input;
function myFunction(){
alert();
}
window.onload = function(){
input = "hello";
myFunction();
}
Note that declaring input outside of these functions isn't necessary (except in strict mode), but it's generally good practice.
The scope of input is restricted to the window.load function()
if you want to access the input from multiple functions make it a global variable.
<script>
var input = "";
function myFunction(){
alert(input);
}
window.onload = function(){
input = "hello";
myFunction();
}
</script>
or passed the input as paramete to the function
<script>
function myFunction(var input){
alert(input);
}
window.onload = function(){
var input = "hello";
myFunction(input);
}
</script>
One way to make it "work" that wasn't mentioned yet is having both the variable and the function part of the onload method:
window.onload = function(){
var input = "hello";
function myFunction(){
alert(input);
}
myFunction();
}
Live test case.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Is there any way to extract value of a variable used in jQuery so that we can use it in JavaScript functions
<script>
var val;
$(document).ready(function() {$('.nav a').click(function(event)
{event.preventDefault();
val=$(this).index();
if(val==0){
$('#hide_main').hide();
$('.main_BSNS').animate({opacity:"show",height:"400px"},'slow')
}//if val==0 ends here
else if(val==1){
$('#hide_main').hide();
$('.main_ACTNT').animate({opacity:"show",height:"400px"},'slow')
}
else if(val==2){
$('#hide_main').hide();
$('.main_devp').animate({opacity:"show",height:"400px"},'slow')
}
});
});
function getCookie(c_name){
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function checkCookie()
{
var username=getCookie("BSNS");
if (username!=null && username!="")
{
$('#hide_main').hide();
$('.main_BSNS').animate({opacity:"show",height:"400px"},'slow')
}
else
{
alert(val);
if (username!=null && username!="")
{
setCookie("BSNS",username,365);
$('#hide_main').hide();
$('.main_BSNS').animate({opacity:"show",height:"400px"},'slow')
}
}
}
</script>
now i want this checkCookie() function to be called by but the alert always show up with an undefined value (as many users predicted) but i am unable to find a solution to this and to write these cookies...(finally i am successful atleast to put my code on this website :-) )
Try fixing the syntax error caused by the missing brackets after myFunction. This will then work:
<input type="button" id="mybutton" value="click me" />
<script>
var x;
$(document).ready(function(e) {
x=5;
});
function myFunction(){
alert(x);
}
$('#mybutton').click(myFunction);
</script>
jQuery is Javascript, it's just a matter of scope for the Javascript variable.
Make the variable global, then you can access it from the function also:
var x;
$(document).ready(function(e){
x = 5;
});
function myFunction() {
alert(x);
}
However, the ready event runs when the entore document has loaded, so the value is only available after the event handler has run. If you call the function before that, the value of the variable is still undefined.
Something like this should work, x just needs to be a global variable:
<script>
var x;
$(document).ready(function(e){
x=5;
});
function myFunction(){
alert(x);
}
myFunction();
</script>
This is just javascript scoping rules. The x defined inside a function is not available outside. You either need to pass that value to myFunction, or you need to define x in a scope that myFunction can see.
multiple ways:
var x; // may be initiated with a value
$(document).ready(function(e){
x = 5;
});
or
$(document).ready(function(e){
window.x = 5;
});
However the ready event has to fire before the value is in the variable. If you ask for it directly in your code you will get undefined.
I recommend to do everything inside your ready event. Then you also have access to your variable.
var x;
$(document).ready(function(e){
x=5;
myFunction(); // call it here or later
});
function myFunction(){
alert(x);
}
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".