Getting variable value out of jQuery [closed] - javascript

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);
}

Related

Using a variable inside a input check in JS

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.

Setting and checking localstorage for a certain value, then performing a function based on the data

I'm trying to set local storage from one page("index.html/settest.html"), and check for it on "index.html". If the check comes back with a certain result, it'll execute a function.
I have written some code for this, but it doesn't work. I don't really know why, so I'm hoping to get some assistance here.
Here's what I have on my "settest.html" page. It's really simple -
<script>
window.onload=setlocalstorage() {
localStorage.setItem("one", true);
}
</script>
So the way I understand it, when the page loads, it should set the value of "one" to true in localStorage.
Here's what I have on my "index.html" page -
<script>
window.onload=setInterval(function() {
var one = localStorage.getItem('one') || '';
if (one != 'yes') {
function hideone() {
var elem = document.getElementById("one");
elem.className = "hide";
}
}
}, 1000);
</script>
From what I understand, this should check localStorage every second for "one", and execute the function "hideone" if it comes back yes(or true).
However, when I go to "settest.html", and then visit "index.html", nothing happens. There are no errors in the console, or anything abnormal showing. I just don't get why it won't work.
Thanks in advance, if anyone needs more information or context feel free to ask!
-Mitchyl
You're not defining the window.onload functions correctly. Either:
<script>
window.onload = function() {
localStorage.setItem("one", true);
}
</script>
Or:
<script>
window.onload = loadFunction;
function loadFunction() {
localStorage.setItem("one",true);
}
</script>
And on your other page:
window.onload = function() {
setInterval(function() {
var one = localStorage.getItem('one') || '';
if (one != 'yes') {
function hideone() {
var elem = document.getElementById("one");
elem.className = "hide";
}
}
}, 1000);
};
Additionally, you're setting localStorage.one to true on the first page, and checking if it's yes on the other page. Not sure if this is meant to be or is a mistake.
None of your functions are correctly defined. It looks like you want to do this:
settest.html:
<script>
window.onload=function()
{
localStorage.setItem("one", true);
}
</script>
index.html:
<script>
window.onload = function ()
{
setInterval(function()
{
var one = localStorage.getItem('one') || '';
if (one !== true)
{
var elem = document.getElementById("one");
elem.className = "hide";
}
}, 1000);
}
</script>
Assuming you want it to check every second to see if it needs to set the class on a specific element to 'hide'.

Access value of variable from if statement Javascript with event onclick

I have the following snippet of code:
var j=4;
var x;
if(j>5){
x=8;
}else if(j<5){
x=1;
}
function write(){
document.write(x);
}
UPDATE: I am having a problem that when I have a button call the function write() it will not print out 1 when it is clicked, it will print out nothing. Calling the function write() separately works, but how do I get that to change for when it is called on by the onclick event?
You must call the function:
function write(){
document.write(x);
}
var j=4,
x;
if(j>5){
x=8;
}else if(j<5){
x=1;
}
write();
Here is a jsfiddle demo

Uncaught ReferenceError function is not defined

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;

Color-cycling an element not working?

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".

Categories