I was wondering if anyone could help me. The problem is javascript isn't storing any variables and is acting up.
<script type="text/javascript" language="javascript">
var name = document.getElementById('text_field').value;
var test = "foobar";
function test_function(){
alert("hello"+test);
}
alert('test '+test);
</script>
The second alert doesnt happen at all, and when i click on the button to trigger the test_function() it alerts out "helloundefined" .
I just don't know what to do, it was working fine then all of a sudden it stopped. I should mention that this is on a php page but that shouldn't make a difference.
If there is no element with the ID text_field, the rest of the code will not run.
try changing:
var name = document.getElementById('text_field').value;
to
var name = document.getElementById('text_field').value || "some default value;
OR
var name;
if(document.getElementById('text_field')) {
name = document.getElementById('text_field').value
} else {
name = "some value"
}
Without seeing the rest of the code, most likely the culprit is this line:
var name = document.getElementById('text_field').value;
If the script block is run before 'text_field' exists, you get an error and the rest of the javascript doesn't execute. The result is that you don't see the alert, and the test variable is never set. You need to call the code after the DOM exists, either by running it in onload (or a ready function in jQuery) or by putting the script block at the end of the page.
Move that script block to bottom of the page. text_field does not exist yet. If you're debugging in a browser, use Chrome or Firefox and make use of the "Console" window in the dev tool bar. It'll tell you things like this...
Related
I'm currently making a website, and I'm creating a "manager" object onload in the body:
body id="real-world" onload="createARSim('ar-world','real-world','phone');">
createARSim(...) returns an object with a bunch of things in it that are useful. One such thing is a
var pageIndex
which monitors the current page.
I want to display the page number somewhere in the web page. Currently I am putting the code inline, like this:
<script> onload.pageIndex.toString(); </script>
the issue is that it throws this error:
TypeError: onload.pageIndex is undefined
And I'm not sure what to do about it. The js code in the constructor runs fine, but I can't find any way to access the returned object once I've finished running the constructor.
EDIT:
ok, I think I might know why it's not working. First, I need to use Document.onload to call the onload object that I've returned. However the bigger issue is how onload works -- I can't call an element of onload inline, because the constructor isn't actually executed yet when I run the inline javascript code (it calls after everything has loaded...).
So I can't just put it inline. I'll have to do some clever editing from the javascript to the div I'm putting it in directly, I think.
You can do the following to solve this problem
window.onload = function() {
var pageIndex = createARSim('ar-world','real-world','phone').pageIndex;
var textNode = document.createElement('text');
textNode.textContent = pageIndex;
document.body.appendChild(textNode);
}
This appends pageIndex to body.
I use the function load for call other page inside other , and i see break all my other codes , in firebug tell me that , id is not defined
My script it´s this :
jQuery(document).ready(function() {
jQuery("#web_perfiles_col_3").load(""+dir_load_footer_users_on);
var auto_refresh = setInterval(
function ()
{
var randnumber=Math.floor(Math.random()*999999999999);
jQuery("#web_perfiles_col_3").load(""+dir_load_footer_users_on+"&rand_n="+randnumber);
},2000);
});
This script break all my other codes , the problem come from the this line :
jQuery("#web_perfiles_col_3").load(""+dir_load_footer_users_on);
I try also using without "" double and single quotes but the problem continue , the case it´s this script it´s inside file with other scripts and in some page this var "dir_load_footer_users_on" no have value , if i delete this line works but it´s the first time i see this problem i don´t know this thing get error for other script because i no defined one var
For me it´s ridiculous that by no defined one var break other scripts ??? , it´s possible fix this or howewer i writte bad or i must do special thing for all works ???
Thank´s everybody for the help in this case
**P.D :** dir_load_footer_users_on it´s one **var**
It would help if we knew what dir_load_footer_users_on was, but maybe something like this?
if(typeof dir_load_footer_users_on != 'undefined') {
jQuery("#web_perfiles_col_3").load(""+dir_load_footer_users_on);
}
There is probably a very simple explanation for this (and likely a much cleaner way to do it), but I'm new and can't quite figure it out. Any assistance would help the learning process...
I have one script that displays one div or another based (show instead of hide) on what a user selects from a dropdown list. Like so:
var PickDiv = (function(){
var _obj = {};
var hideShow = function(elem){
if($(elem).val() === '1'){
$("#slider_action").show();
$("#slider_dollar").hide();
}else if($(elem).val() === '2'){
$("#slider_dollar").show();
$("#slider_action").hide();
}else{
$("#slider_dollar, #slider_action").hide();
}
};
_obj.checkValue = function(){
hideShow($('#build_opt'))
};
var events = function(){
$('#build_opt').change(function(){
hideShow(this);
});
};
$(document).ready(function(){
events ();
checkValue ();
});
return _obj;
}());
This works great and displays the right div based on what is selected from the dropdown. I thought I could reuse this same idea later in my code to have the same effect. Once the div is displayed (after making a selection related to script above), I need to provide another dropdown with additional options. The user will select one of these and then a div will display. So, I figured, I could use something like this:
var RunRate = (function(){
var _obj2 = {};
var hideShow_2 = function(elem_2){
if($(elem_2).val() === '6'){
$("#db_sign").show();
$("#app_down", "#in_redem", "#site_vis", "#cont_ent" ).hide();
}else if($(elem_2).val() === '7'){
$("#app_down").show();
else{
$("#app_down", "#in_redem", "#site_vis", "#db_sign", "#cont_ent" ).hide();
}
};
_obj2.checkValue_2 = function(){
hideShow_2($('#action_type_2'))
};
var events_2 = function(){
$('#action_type_2').change(function(){
hideShow_2(this);
});
};
$(document).ready(function(){
events_2 ();
checkValue_2 ();
});
return _obj2;
}());
Of course, this doesn't work. I tried a number of different things with no luck. Note that if I exclude the first script from my code, the second script works fine, so I know it works. I'm guessing it has something to do with the two scripts sharing a variable or something about jquery that I'm clearly missing.
Any help would be appreciated. Overall, looking to be able to do a number of these types of dependent dropdowns without interfering with one another.
Thanks for your help!
UPDATE:
Note that if in the second script, I replace:
$(document).ready(function(){
with
$( window ).load(function() {
then the problem is solved. So, clearly the problem is related to the document.ready interfering with each other, but I don't know how to fix this without this "hack" above especially if I want to use more of these dependent dropdowns. Is there a way to pass a different variable and call that instead of document?
UPDATE 2
Figured out the problem...my original code was throwing an error due to an undefined reference (checkValue). That error was causing the document ready to not work in the second function. Referenced a more detailed explanation in my answer below.
Figured out the problem thanks to this answer to a related question pointed out by #skmasq. #JustinWood was onto something with his comment on my original question. Turns out that my scripts were throwing an error ("Uncaught ReferenceError: checkValue is not defined"), which was not allowing the document ready function to work properly.
Here's the critical part of the answer :
It is important to note that each jQuery() call must actually return. If an exception is thrown in one, subsequent (unrelated) calls will never be executed.
This applies regardless of syntax. You can use jQuery(), jQuery(function() {}), $(document).ready(), whatever you like, the behavior is the same. If an early one fails, subsequent blocks will never be run.
Could be that $(document).ready() overwrites the initial job? It doesn't matter if you use different functions/variable names ...$(document).ready is the same ...
I'm trying to display a Javascript prompt for the user to enter data (as prompts are used for). But, it won't show. window.alert shows, and so does window.confirm. But, not prompt.
Here's the code I'm trying to run:
var is_expired = document.getElementById("is_expired").value;
if (is_expired == "yes") {
alert(is_expired);
var answer = prompt("Are you sure you?");
alert(answer);
}
When this runs, the if statement is entered. The first alert displays "yes" as it should. But, then, it skips the prompt line. The next alert displays saying "Undefined".
Now, if the only thing I change is the keyword prompt, it will work, as such:
var is_expired = document.getElementById("is_expired").value;
if (is_expired == "yes") {
alert(is_expired);
var answer = confirm("Are you sure you?");
alert(answer);
}
When I run this, the confirm box appears. If I click Okay, then the next alert says "true" and if I click Cancel the alert says "false".
So, the big takeaway here is that there isn't a syntax error that's causing the Javascript to stop. It's actually skipping over that single line and continuing execution. What's wrong with that line? I've checked multiple sites to ensure it's correct.
Adding the second "default" parameter does not help either. I tried that. Also, There are no Javascript errors to indicate the problem.
I went here and changed it to my code (I hardcoded is_expired to be yes), and it works there.
Any help would be fantastic. Thanks.
EDIT: To be clear, I'm not relying on W3school's example to be accurate, I used their "try it out" page to test my own code. I also did this on jfiddle and it worked fine. Using the console to check the function returns "undefined".
EDIT2: Actually, scratch that. I accidentally hit enter again when there was no command in the console. The actual output for prompt is:
[12:07:55.940] [object Function]
prompt should pretty much work in every browser. One possibility is to check if you didn't accidently override this function somewhere in your source. If you type prompt in the browserconsole when on your site, it should state something like this:
> prompt
function prompt() { [native code] }
// or put in your code:
alert(window.promt);
Otherwise it got overridden somehow (most likely by forgetting the var keyword):
> prompt = function(){alert("foo!")}
> prompt
function (){alert("foo")}
// calling prompt() would now pop an alert box
As suggested, something in your code has overridden the window.prompt method with function prompt(s) { window.status = s }. Not sure if this was intentional or not.
There are a few methods you can use to "restore" the original prompt.
You can backup the original at the very start of your page:
var originalPrompt = window.prompt;
// Whatever code is on your page
function prompt(s) { window.status = s }
Then use originalPrompt instead:
var answer = originalPrompt("Are you sure you?");
You can delete window.prompt; (or set window.prompt = null;), though this may not work in all browsers.
You can create an iframe (which creates a new window environment), and then "steal" the prompt from there.
var i = document.createElement('iframe');
i.style.display = 'none';
document.body.appendChild(i);
window.prompt = i.contentWindow.prompt;
When declaring variables in a function, make sure you use the var keyword so it doesn't clobber the global namespace. It sounds like you're doing this somewhere:
function my_thing() {
var i = 0;
var j = 0;
prompt = "What the heck";
}
Omitting the var keyword puts prompt in the global namespace, clobbering the default prompt function.
I'm building a website and here is basically what I want to achieve using JavaScript:
if browser language = fr then get the text from languageFr.json
else get the text from languageEn.json
Here is what my code looks like for now:
My JSON
{
"h2": "random title",
"p": lorem ipsum
}
My JavaScript, in the head of index.html
<script text="text/javascript">
var lang;
function detect() {
var userLang = navigator.language || navigator.userLanguage;
if (userLang == "fr") {
lang = JSON.parse("languageFr.json");
} else {
lang = JSON.parse("languageEn.json");
}
}
$(document).ready(detect());
</script>
And then in my HTML's body:
<h2><script>document.write(lang.h2);</script></h2>
However this does not seem to work. Chrome's console tells me lang is undefined.
What am I doing wrong?
Thank you
The code <h2><script>document.write(lang.h2);</script></h2> executes before document ready. That's why your detect method has bot been called at the moment and lang has not been initialized.
You use JSON.parse method in a wrong way
Well, one thought is that the Javascript in this block
<h2><script>document.write(lang.h2);</script></h2>
is executing before the function has run.
That Javascript will execute as soon as the browser reaches it; the browser will pause parsing the page to do this. However, your detect function looks like it's waiting for the document ready event to run.
So, the document.write() call happens before the detect() method is called, and lang has no value.
Egor4eg is correct about the problem (actually most of the answers are). I'd advise you to use a different method for filling in any elements that should have language-specific text. Here's a possibility.
<div class="i18nstring" data-message="h2"></div>
//Put this at the bottom of your detect() function (so it's only called after $ ready)
$('.i18nstring').forEach(function() {
$(this).text( lang[this.dataset.message] );
}
That might need just a little bit more work (mostly on the data-message thing) to be fully cross-browser compatible, but JQuery can help with that. Note that each i18nstring node does not have to be a div.