javascript compute mistake (calculator) - javascript

I need to make a calculator using JavaScript, HTML and CSS. Everything worked out fine until I came to coding the compute (=) button.
This is my HTML:
<input type="button" value=" = " onclick="compute()">
This is my JS:
function compute() {
var input_var = document.getElementById('input');
ans = Math.floor(+eval(input_var.value));
document.getElementById('answer').value = '=' + 'ans';
}
If anyone that knows how to solve what's wrong, I would greatly appreciate it if you could reply.

First of all, you should post the whole code to get accurate solution!
Probably these could be some of the errors:
Set id attribute of your = button with value "input"
3rd line should be: ans = Math.floor(eval(+input_var.value));
4th line should be: document.getElementById('answer').value = '=' + ans; as StaticBeagle has also mentioned.

You should be lucky that you made the mistake to put the variable in quotes. That's why you don't get a value other than the literal string =ans(maybe, we don't know as you didn't post all code that's needed to give a better answer).
Back to why you're lucky.
Never use eval! eval is evil. (Unless you know what you do, but you don't the next couple of years). To parse a number, you'd use Number(input_var.value).
The next error is that you create a global variable by omitting one of var, let, const for your ans declaration.
The next thing you shouldn't do is to use inline javascript. We use eventListener instead. As said before, it's impossible to answer more specific as your question lacks too many details - however I'll show you how you get a value by pressing a button in the console.
document.getElementById('foo').addEventListener('submit', e => {
// prevent submitting the form (I guess another error in your code)
e.preventDefault();
const value = Number(document.getElementById('input').value);
console.log('The value is: ' + value);
}, false);
<form id="foo">
<input type="number" id="input">
<input type="submit" value=" = ">
</form>

Not sure if ans is a local or global variable, but if its intention is to be a local variable then you should have it like this:
var ans = Math.floor(eval(+input_var.value));
Also, because you're setting the value of your element to '=' + 'ans' you're actually setting it to the actual string 'ans'. If you want to refer to what ans is you should write it like this:
document.getElementById('answer').value = '=' + ans;

Related

Javascript - Use document.getelementbyid().value with a variable

I'm trying to capture the value of a text field on an HTML form using document.getElementById(my_field).value where the variable my_field is passed to my function dynamically, but am hitting a wall.
How do you use a variable in this context?
The function just doesn't seem to parse the contents of the variable my_field, instead treating it as a string no matter whether I use quotes, square brackets or curly braces.
function myFunction() {
var my_field = arguments[0];
var current_value = document.getElementById(my_field).value;
alert ("Current Value: " + current_value);
}
I'm doing it this way because I have multiple records on a form and each row has its own unique id for the required field.
Running the above just does nothing. The alert never pops which I assume is because current_value never gets set.
To add further detail - I tried to simplify everything for the purposes of this question as there's lots of other unnecessary complications that will only detract from the main issue - on my HTML form is a text field which calls my function on onChange
onchange="enforce_multiples('quantity[<?php echo $line_id; ?>]',<?php echo $product['minimum'];?>)"
I've checked that arguments[0] and [1] are being captured correctly by outputting their values to an alert. Everything works fine up until I try to set the quantity_entered value.
<script>
function enforce_multiples() {
var line_id = arguments[0];
var quantity_increments = arguments[1];
var quantity_entered = document.getElementById([line_id]).value;
alert("QE" + quantity_entered);
//var quantity_mod = quantity_entered % quantity_increments;
//var revised_quantity = quantity_entered - quantity_mod;
//alert("RQ: " + revised_quantity);
//document.getElementById([line_id]).value = revised_quantity;
}
</script>
Checked the console and I receive the error: Uncaught TypeError: Cannot read property 'value' of null on the geElementById line
You should write document.getElementById(my_field) instead of document.getelementbyid(my_field).
OK so I got to the bottom of this in case anyone is interested.
In order to use a variable in document.getElementById() you simply add the variable name with no quotes.
var my_variable = "field1";
document.getElementById(my_variable);
The reason this wasn't working on my form was because the text fields only had the name parameter and not an id parameter.
So I needed to change:
<input type="text" name="field_name" value="1234" />
To
<input type="text" name="field_name" id="field_name" value="1234" />
And that sorted it. Otherwise I was just getting generic NULL error messages in the console.

JQuery: if element does not contain text

I am trying to write a statement along the lines of: 'if given element does not contain the following text, do something'.
I have tried using :contains as such:
var openingHours = $('.opening-listing:nth-child(' + new Date().getDay() + ')');
if($(openingHours + ':contains("Closed")').length > 0){
//Do something
}
But am getting syntax errors.
Would anyone know what I've done wrong here, or if there is a better way of going about this?
openingHours is a jQuery object, not a css selector. You can use .text(), .indexOf(), which :contains() uses internally
if (openingHours.text().indexOf("Closed") === -1) {
// do stuff
}
Use the :not() CSS selector.
var openingHours = $('.opening-listing:nth-child(' + new Date().getDay() + ')');
if($(openingHours).find(':not(:contains("Closed"))').length > 0){
//Do something
}
They way I understand your question is that; you have an HTML element with some content (text or number). And you want to use that content in decision making such as if-statement.
Here is an example of the code I made in repl.it, click here.
I give each element a unique id name, so that I can call it in JavaScript for decision-making. Then I add onClick which invokes a function in JavaScript.
<form>
<div>
<input type="text" id="inputName" placeholder="Your name">
</div>
<input type="submit" onClick="getName()" value="Submit">
</form>
Next step is to use document.getElementById(tagName).value which receives the content you have written in the inputfield after you click on submit button. And set the value into a next variable instead of copying the whole line of code. Last but not least, I have also added an example if you have jQuery library, I prefer using jQuery approach because it is less code and easier to understand for beginners.
function getName(){
// Gets the value from HTML and inserts the result in new variable called inputName
var inputName = document.getElementById("inputName").value;
// This works only if you have jQuery library included in html part
//var inputName = $("#inputName").val();
// If-statement
if(inputName === "Peter"){
alert("Name is = " + inputName);
} else if(inputName === "Jacob"){
alert("Name is = " + inputName);
}
}
I hope this gives you different perspective on how to solve your problem. Good luck!

Javascript function cannot be executed twice

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.

jquery getting value from input

This has me stumped, and should be pretty simple.
I have an input in my html:
<input type="text" id="fafsaNbrFam" name="fafsaNbrFam" value="<%=nbrFam%>" class="hidden" />
System.out.println(nbrFam); // Works, gives me "6"
Then my js code:
$("#submit").click(function(e) {
var numEntries = 0;
var fafsaNbr = 0;
$("input[name^='name_']").each(function() {
if (this.value) {
numEntries++;
}
});
// EVERYTHING ABOVE HERE WORKS
fafsaNbr = $("input[name=fafsaNbrFam]").val();
alert(fafsaNbr + "X");
// WHERE THE 6 is I want to put the variable fafsaNbr, just hardcoded for now.
if (6 > numEntries && !confirm("The number of members you listed in your household is less than the number you indicated on your FAFSA. Please confirm or correct your household size. ")) {
e.preventDefault();
}
});
On my alert to test this, I get "undefinedX", so basically my jquery to get the value is coming up undefined.
EDIT: So it turns out my code wasn't the problem, but the placement of my input. Even though the original input placement was being processed, once I changed it, it all worked properly. Needless to say, I am still stumped.
You are missing the quotes around the name value. Try:
fafsaNbr = $("input[name='fafsaNbrFam']").val();
Your code is working fine,
I just added your code to jsFiddle and it works
Live EXAMPLE
Could you please make sure, the java scriplet is loading inside the value tag properly or not by checking the view source in browser?
Try to parse the value of the input like this:
fafsaNbr = parseInt($("input[name=fafsaNbrFam]").val());
Or Check whether the $("input[name=fafsaNbrFam]") is undefined or not.

Form text field variable is showing undefined in Javascript

This is my first post, anyway I'll get straight to the point.
I have a form that when a user writes they're name in, Javascript saves the value to the global variable "ch_name". When I access this variable through an alert at any point on the site it always shows the correct value that I entered. However, it only works for alerts, when I try reference the user by using the variable it always shows as undefined.
I've tried re-ordering the code in case it hadn't loaded correctly and this hasn't yielded any results either. I've begun wondering whether I've referenced it right at all as I'm still fairly new to JavaScript.
As you'll probably find out my code is a mess but here's what I've got.
var ch_name; //my global variable
var data = new Array(); //I've taken a snippet out of an array of 8.
data[0] = '<p>Question 1</p>' + ch_name + "\n" + //ch_name is referenced on this line.
'<button onclick="results1()">Click Me</button>' + "\n" +
'<button onclick="results2()">Click Me</button>' + "\n" +
'<button onclick="results3()">Click Me</button>';
function charName(form) { //This is the code that changes the global variable ch_name.
ch_name = document.nameform.user.value;
ranData = Math.floor(Math.random() * data.length);
document.getElementById("placeholder").innerHTML = data[ranData];
}
The html snippet:
<form NAME="nameform" method="GET">
<p>Enter your character name:</p> <input type="text" name="user" value="" />
<input type="button" value="Start" onClick="charName(this.form)"/>
</form>
<div id="placeholder"></div>
Referencing the ch_name through an alert anywhere gives me the correct result, blank on page load and after the string is entered it gives the correct name. But anytime I reference it through the array variable it shows an undefined. This is not the full code but I'm certain there's no conflicts in variable names etc. I've scanned it a good few times, I'm certain it's just me being an idiot.
Is there a work around for this? I'm in a place ready to drop the whole code behind ch_name entirely to focus on other areas of the page.
Thanks for reading and any help.
I think that your problem is that when your data array is generated, ch_name doesn't have a value, so it comes out as blank. Even when you change ch_name, the data value won't be re-generated with the correct value.
A solution to this might be having a regenerate_data function that re-generates your data data array whenever you change the global character name.
The data won't change the way you seem to think.
I think for you the best bet would be to replace data Array with a function.
Now the ch_name parameter will be created dynamically every time you run the function. i.e. every time the button is pressed, which will update the data.
How do you change the data in a page?
var ch_name; //my global variable
function charName(form) { //This is the code that changes the global variable ch_name.
ch_name = document.nameform.user.value;
ranData = Math.floor(Math.random() * data.length);
document.getElementById("placeholder").innerHTML = getranData(ranData);
}
function getranData(num){
if(num==0)
return '<p>Question 1</p>' + ch_name + "\n" + //ch_name is referenced on this line.
'<button onclick="results1()">Click Me</button>' + "\n" +
'<button onclick="results2()">Click Me</button>' + "\n" +
'<button onclick="results3()">Click Me</button>';
else if (num==1) ; ///...and so on
}

Categories