Javascript function cannot be executed twice - javascript

I'm kind of new to Javascript and I've bee wondering for hours how to solve my problem. I have a litle function associated to a button. It work once but I cannot get it to execute after the first time.
function CheckEmpty1(){return "false";}
function Generate(){
if(CheckEmpty1() == "true"){
alert("Please fill all mandatory field.\n\nAll missing field are black colored.\n\nPlease also make sure to make a choice for all radio button.");
}
else{
document.getElementById('TemplateOutput').style.display = "block";
lol = "lol";
document.getElementById('TemplateOutput').value = lol;
lol = "test2";
}
return;
}
"TemplateOutput" is a simple textarea centered in the browser. The code is originally more complicated than that but while doing the test to ensure the problem was not coming from somewhere else, it reduced to that but still doesn't work.
The second "lol = "test2";" is just to check that if I make a change to the variable, it is suposed to apply the second time I hit the button.
it seems to be basic for me but I can't figure out why... any help?
thanks.
EDIT:
I think I found the source of my error in my original script. My original code look like this:
function Output(){
Output = "CSD Troubleshooting: " + Troubleshoot + "\n";
return Output;
}
function Generate(){
FillVars();
GenerateOutput = Output();
alert(GenerateOutput);
}
function FillVars(){
Troubleshoot = document.getElementById('Troubleshoot').value;
}
I reduced it to the minimum but it still behave the same way.
The problem is coming from the Output() function because it work fine if I do it like this:
GenerateOutput = document.getElementById('Troubleshoot').value;
alert(GenerateOutput);
or
GenerateOutput = Troubleshoot;
alert(GenerateOutput);
BEHAVIOR: I click the button. The alert is filling like it is suposed to be. The second time I click the button, it just do nothing.
regards,

Updated Answer:
Your edit changes things markedly. The central issue is here:
function Output(){
Output = "CSD Troubleshooting: " + Troubleshoot + "\n";
return Output;
}
The first time you run that function, you replace the function with a string. The Output symbol is a reference to the function.
It looks like you might have a Visual Basic background. In JavaScript, you simply do this:
function Output(){
return "CSD Troubleshooting: " + Troubleshoot + "\n";
}
or if you want it in a variable first, declare the variable (with var) and probably to avoid confusion use a different name:
function Output(){
var result = "CSD Troubleshooting: " + Troubleshoot + "\n";
return result;
}
Original Answer:
The second "lol = "test2";" is just to check that if I make a change to the variable, it is suposed to apply the second time I hit the button.
It won't, because your previous
lol = "lol";
...line runs, setting it back to "lol". You'll never see the code put "test2" into the input.
The line
document.getElementById('TemplateOutput').value = lol;
copies the value from lol to the value property. It does not make the value property a reference to the variable lol. Changing the variable later has no effect, because there is no continuing link between it and the value property.
Since the if block in your code will never run, let's just look at the else block. Here, in detail, is what happens:
// 1
document.getElementById('TemplateOutput').style.display = "block";
That looks in the DOM for the element with the id "TemplateOutput", and sets its style object's display property to "block".
// 2
lol = "lol";
That assigns the value "lol" to the lol variable. Unless you've declared lol somewhere you haven't shown, it also creates an implicit global variable. Details: The Horror of Implicit Globals.
// 3
document.getElementById('TemplateOutput').value = lol;
That copies the value "lol" from the lol variable into the value property of the input.
// 4
lol = "test2";
That copies the value "test2" into the lol variable.

Related

JavaScript only code returning "Cannot read properties of undefined" when object property should be defined

I have been trying to figure this out for two hours. The object has the all of the details there, it should be able to find those details once called. But it isn't. Thank you for any help.
if (localStorage.getItem("contactDetails")){
println("Name: " + contact.firstName);
}
else {
var firstNameVar = prompt("What is your desired first name to log?");
var lastNameVar = prompt("What is your desired last name to log?");
var phoneNumVar = prompt("What is your desired phone number to log?");
var contact = {
firstName: firstNameVar,
lastName: lastNameVar,
phoneNum: phoneNumVar
}
localStorage.setItem("contactDetails", JSON.stringify(contact));
}
I have tried changing between localStorage and directly calling it, I have tried using the object["item"] method rather than just object.item, and a few other things.
EDIT: Going to have to come back to this one. I have tried every single suggestion and it still is not working. My brain is extremely fried from 3 hours of one problem. This is the entire code, there is no more code than this. I'll get back at another time for this. Thank you for your patience!
Try this :
let contact = localStorage.getItem("contactDetails")
if (!!contact){
println("Name: " + contact.firstName);
}
else {
let firstNameVar = prompt("What is your desired first name to log?");
let lastNameVar = prompt("What is your desired last name to log?");
let phoneNumVar = prompt("What is your desired phone number to log?");
contact = {
firstName: firstNameVar,
lastName: lastNameVar,
phoneNum: phoneNumVar
}
localStorage.setItem("contactDetails", JSON.stringify(contact));
}
PS : Avoid using var , instead use let or const .
Reason why I insist not to use var instead use let or const is as follows :
This code will print Global Variable even though globalVar is defined inside if statement because of scoping property of var .
if(true){
var globalVar = "Global Variable"
}
console.log(globalVar);
This code will give you an error , as you have not defined scopedLet outside if and still trying to access that variable.
if(true){
let scopedLet = "Scoped Let variable"
}
console.log(scopedLet);
Same is the case with const.
if(true){
const scopedConst = "Scoped const variable"
}
console.log(scopedConst)
You've got two problems going on here.
One problem is that when you call localStorage.setItem("contactDetails", JSON.stringify(contact));, you are storing a string, so when you call localStorage.getItem("contactDetails") you get a string back. To fix this you need to wrap it in a JSON.parse(), so it looks something like this: JSON.parse(localStorage.getItem("contactDetails")).
The second problem is that you are calling contact.firstName before you define the variable contact. To fix this you need to change your if statement to look like this: if (localStorage.getItem("contactDetails")){ let contact = JSON.parse(localStorage.getItem("contactDetails")) println("Name: " + contact.firstName); }
Hope this makes sense.
There are two issues in your code that I have noticed.
Issue #1
You are asking for the value of contact.firstName before it is defined.
To fix this, you need to change the inside of the if statement to the code below.
let t = JSON.parse(localStorage.getItem("contactDetails"))
console.log("Name: " + contact.firstName);
Note: I changed the syntax a little as it didn't look like JavaScript.
Issue #2
When you call JSON.stringify() on your JSON and store it in localStorage, you are storing it in a string. However, when you are getting the key, you are not parsing the JSON. To change it back, you need to use the code below when getting the key.
JSON.parse(localStorage.getItem("contactDetails"));\
It says undefined meaning the variable contact.firstName is not defined
u need to define first the object contact before your if else
let contact = {
firstName = "john"
}
in here u have contact.firstName
and it will print "john"

Free Code Camp weather app, toggle won't work

Here is my Javascript code.
$("#changetemp").click(function () {
var temp = $("#temperature").html;
var final_letter = temp[temp.length-1];
$("#temperature").html(function ()
{if (final_letter == "F") {return celsius;}
else {return fahrenheit;}});});
});}});});
It is supposed to toggle the temperature between celsius and fahrenheit but does a big fat nothing. I've googled and changed a few things (e.g. gone between val, html and text, and tried charAt but I can't get it to do anything, let alone the right thing. Any suggestions would be very welcome.
Edit: "#changetemp" is the button you click to toggle between temperature (ideally).
"#temperature" is where the temperature displays (and it does, but then won't change).
Also tried:
console.log(final_letter); (which gave the correct letter in the console)
console.log(celsius); (which reports as 'undefined') as does console.log(fahrenheit);
These two are defined earlier via a JSON
$.getJSON( url, function(location){ var celsius =
$("#temperature").html(Math.round(location.main.temp - 273) + "°C");});
and I tried to make them be global variables by putting
var celsius;
var fahrenheit;
after the beginning of the first function (which surrounds everything else) but I'm guessing that didn't work.
More:
Googling suggests that variables cannot begin with a number. Is this what is stopping me here?
1. I've managed to show the temperature though, just not change it.
2. How do you get round that? I tried changing the code so that 'celsius' would give 'Temperature: 10C' rather than '10C' but that didn't solve it.
i assume the error is in the line var temp = $("#temperature").html;
Does it help if you change it to var temp = $("#temperature").html();?
html is a jQuery function, so you need to call it with the parantheses. Otherwise temp will not contain the content of the #temp element, but rather a reference to the html method. Therefore you don't get the last letter of the content.

Accessing a local variable outside a function

I know this will be a very obvious answer for must of you guys, but please keep in mind that I recently started learning JS and this is one of the only principle that I don't understand.
I am trying to find a way to make a variable inside a function be global. I will show you my code so maybe you will understand:
$('#inputSubmit').click(function() {
addText_1("Good, your character's name is " + getInput() + ".");
condition1 = true;
});
if(condition1 == true) {
addText_1("Now")
};
I am trying to find a way so that the if statement can access the condition1 variable in order to execute the folowing line of code.
For some reason, the if statement cannot access the condition1 value inside the click event.
Also, maybe you know a better way that this way to do what I am trying to do. Basically, I am trying to write code that will use the addText_1 function if the #inputSubmit was clicked. If you know another way of doing this, I would like to know.
Thank you very much for the help and I am sorry if this question wasn't very clear.
the basic problem is the time axis of your code. althought the code is build with 2 blocks, the last block actually run BEFORE the first block
$('#inputSubmit').click(function() // occurs when the user click (#2)
{
addText_1("Good, your character's name is " + getInput() + ".");
condition1 = true;
});
if(condition1 == true) // occurs when the page load (#1)
{
addText_1("Now")
};
i guess what you are trying to do is:
$('#inputSubmit').click(function()
{
addText_1("Good, your character's name is " + getInput() + ".");
addText_1("Now")
});

jQuery object never changing except for first time

I ran into a problem with an object which I'm trying to modify. The object has a certain amount of keys in the format key_yyyy-mm-dd. When certain inputfields lose focus, I trigger a function to modify the object. This function is as follows:
function updateHotelBooking()
{
$(".no_hotel").each(function(i) {
var day = $(this).attr('name').match(/\[(.*?)\]/)[1];
hotelBooking["key_" + day] = parseInt($(this).val());
});
}
.no_hotel are the textboxes that trigger the function, and they also provide a value which I want to put in my object.
Now, say I put 3 in my first text box, a console.log will return the following object:
Object
key_2011-08-21: 3
key_2011-08-22: 0
key_2011-08-23: 0
key_2011-08-24: 0
key_2011-08-25: 0
However, the next time I put something in the textbox (or another textbox that should trigger the function), it DOES trigger, however the object returned remains the same. So instead of changing the first number to, say, 5, it will just return 3 again.
I have no idea why. My code seems pretty straightforward, and a console.log of day and $(this).val() returns the right values. It's just my object that doesnt get updated.
Does anyone have any idea? Thanks a lot!
EDIT:
hotelBooking is initialized right after $(document).ready():
var hotelBooking = {};
The method that calls updateHotelBooking is the following:
$(".roomrequest").blur(function()
{
updateHotelBooking();
});
EDIT2: JSFiddle: http://jsfiddle.net/pBYeD/2/
it has to do with something with the console rather than your code, if you change the logging code to this, you will see that you have the correct values:
function updateHotelBooking()
{
$(".no_hotel").each(function(i) {
var day = $(this).attr('name').match(/\[(.*?)\]/)[1];
hotelBooking["key_" + day] = parseInt($(this).val());
**logObject(hotelBooking);**
});
}
function logObject(hotelBooking){
for(var i in hotelBooking){
console.log(i+": "+hotelBooking[i]);
}
console.log("------");
}
Are you sure the problem does not come from the debugger output?
As far as i can see in my chrome output, if i let the fiddle as is, the object doesn't appear to change in the console (just the number on the left takes a +3). However if I add something like console.log(hotelBooking["key_" + day]); just before or after, it's shown as changing.

Mind boggling javascript failure at handling some basic addition!

This is killing me! I'm trying to add the values of four fields together, and I get allllll kinds of wierd results!
The code I have so far:
$('input.percent').change(function() {
var totalup = 1;
var totalup = totalup*1;
$('input.percent').each(function(){
var current = $(this).val();
var curvalue = current * 1;
console.log(curvalue);
console.log(totalup);
var totalup = curvalue + totalup;
});
});
This should be ungodly simply. Start with a value of zero, get the value of each input, add it to that totaling value. The console log always shows UNDECLARED or NaN for totalup, but if I remove the last decleration of totalup (where it adds more to totalup) it suddenly doesn't become undefined or Nan.
Why is this not ungodly simply!!! I must be missing something dumb, or Javascript just STINKS!
Thanks in advance for your help!
var percentInputs = $('input.percent');
percentInputs.change(function() {
var total = 0;
percentInputs.each(function(){
total += Number($(this).val());
});
});
Update
Caching those selectors would be a good idea too.
the main problem is the declaration of already declared fields. Leaf the var keyword for the second and third assignment of totalup and it'll work.
add the parseInt() while the calculation for an example
var totalup = parseInt(curvalue) + parseInt(totalup);
Okay! Here is where the issue was arising!!!!
When you write:
var FOO = 'whatever';
...Inside of a function, it is a LOCAL VARIABLE! If however you simply go:
FOO = 'whatever';
You hit the global variable (variable declared outside of the function).
So while the code above is the solution, this is where the explained solution to the problem exists!

Categories