I am a new student understanding javascript. I am currently having a difficult time understanding a simple concept on storing a variable on my calculator side project. My problem is when a operator (+,-,/,*) is clicked, I want to store the first value as a variable (first user input). Then after the user clicks on the digits again, the display screen will clear and display the second variable (or the second user input). Then if the operator button or equals button is pressed it will calculate the two variables (so var + var2). I have used a global variable for variable1, but I am having trouble assigning the second variable with the user input after clearing the item. I have a feeling there is a simple answer to this question, but I want to know what I am fundamentally doing wrong so I can start reviewing all the topics I need to do cover again. Anyways any help will be great! Thanks
'http://codepen.io/kevk87/pen/EVoEaa`
First thing, you have a syntax error in your statement that is causing jQuery to not select the right element. I have fixed that in my snippet below.
Second, you need to implement the equal operator to put all of this together. Meanwhile, to address your problem and point you in the right direction, You aren't really capturing the second element. Everytime the user clicks on an operator, you are reassigning the value that is on the screen to 'number' variable, then clearing the screen and assigning the value that is on the screen(which is clear because you just cleared it) to 'number2'.
One way to get around this is to check and see if the 'number' variable has a value, if so then you assign the next value to the 'number2' variable. Here's a snippet of code that does this.
$(".operator").on("click",function() {
if (number == null) {
number = $("#screen").html();
}
else {
number2 = $("#screen").html();
$("#screen").html("");
}
});
You forgot the # selector on the line $("screen").html("");, jQuery won't select the correct element. Also you haven't implemented the equal operator yet.
$(".operator").on("click",function() {
number = $("#screen").html();
$("screen").html("");
number2 = $("#screen").html();
});
Related
I have this form, an official form (a character sheet for use at an Organized Play Event for a role-playing game, if it matters to anyone), that someone kindly turned into a fillable PDF form. I asked a question earlier about checkboxes and auto-calcualtions, and got that to work...but now I need to account for another variable (situational doubling of the Proficiency Bonus) in some of my calculations. Unfortunately, this variable is not represented anywhere on this form, and I can't just add fields to the form (it being an official form, at least when printed). Without adding more fields to the (printed) form, how can I account for this additional variable?
I thought about just allowing the user to override the auto-calculation by typing in the field, but I can't figure out how to make that happen. Is this a good solution? Is this relatively simple to code?
If your answer involves adding code to my form, please include a code snippet I can modify, and a description of where I should insert it into my existing code, or if there is somewhere else I need to be adding it instead.
Code Sample:
//check bonus = stat bonus + applicable proficiency bonus
var profUse = this.getField("SklAcrProf").value;
var stat = Number(this.getField("DEX1").value);
var profVal = Number(this.getField("Proficiency Bonus").value);
var check = Number('-2');
if (profUse != "Off"){
check = stat + profVal;
}
else{
check = stat;
}
event.value = check;
If the form only needs to remain the same, when printed, the simplest solution may be to go ahead and add the fields that you need. You can set them up, so that they are "visible but doesn't print". This option can be selected in the Form Field drop-down list, in the Text Field Properties, General Tab, under Common Properties.
This way, you can still incorporate the data in your formulas, but it has no affect on the printed document.
I'm trying to write a custom function that will count and return the number of cells that contain information on a singular column. I'm using a range of A(x):Z(x) and I can't seem to dynamically pass these so I can get a user defined range everytime.
Edit: Current Error I'm receiving right now says: Missing ) after argument list. (line 10, file "Number Of Updates")
So far I have this....
function updateNum(row1,col1,row2,col2)
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName("report status");
var r = s.getActiveRange(row1+col1:row2+col2); <---Line with error
return (range.length-2)/2
}
any suggestions on how I could make this pass the range?
thanks,
Alexander
change the line for:
var r= s.getRange(row1, col1, row2-row1+1, col2-col1+1);
but that won't solve your problems has the line just behind is a non sense. "range" is not declared. I don't see where you want to go exactly. please write some pseudocode.
If what you want is to count the number of cells that got informations in it, just use the spreadsheet native function
counta()
Its not possible with custom functions because they are deterministic. That is, they will return the same result given the same input.
In your case even if you fix the bugs you are still not passing the actual input just its range limits. Thus if the data inside the range changes you still pass the same input limits thus will return the previous cached result.
There are ways arround that like passing an extra parameter that always changes like 'now()'but that has performance problems as it will recalculate constantly.
I'm looking for a way to get all the information out of localStorage. The trouble I'm having is I don't know what the data will be as it is user generated.
So here what happens, a user inputs some text, it uses javascript to manipulate it depending on what check boxes they have ticked on the input form. these boxes are for symbols for example if they tick the box for # then the text + the #At (symbol then word) will be placed in local storage with the other half of the pair as a Boolean (1 or 0 in this case) representing whether its been checked.
the exact pair would look like this:
someString..#At | 1
someString..#Hash | 0
etc.
It should also be noted that this is intended to be used in a Chrome Extension so compatibility in other browsers is not a requirement for me (although it could well be usful to others reading this as I can't find anything else covering it on the web).
So, if there anyway I can extract all the values in localStorage without actually knowing the name of each key?
Is it possible to use any kind of wild card or regular expression maybe, I have tried this but should make it work using a for loop.
Thanks,
Wez
window.localStorage.key is the solution.
Example:
var i = 0,
oJson = {},
sKey;
for (; sKey = window.localStorage.key(i); i++) {
oJson[sKey] = window.localStorage.getItem(sKey);
}
console.log(oJson);
I am completely confused here. So I am looking for a solution for the following problem:
I want to trigger some function(for now an alert box) using jQuery on an input field. Conditions are:
Input field always maintains the focus.
Input is fed from a USB device, which acts just like a keyboard input. So for 10 characters, there will be 10 keydown and keyup events.
Once input is filled with 10 characters, respective alert box should pop out.
Now the problem I am facing, how do I find out that input fed in is not equal to 10 characters, so throw an error alert box.(lets say just 5 chars came in input, how do I figure out the final count is 5, because there will be 5 keyup events)
You could show a message underneath/beside the input box instead of popping an alert box.
E.g. on every keyup event, check the string length, and if it's not 10, show that message.
If you really, really have to resort to alert box, you could do a timeout check, e.g. only perform the validation after 1000ms of key event inactivity. This could get very annoying on the user though.
You really have two problems here. One is just understanding the jQuery syntax (see the second part to my answer), and the other is - what is the best way to understand WHEN to throw up an error box.
To answer the second question first, my recommendation would be to not use an alert box to warn the user as they tend to be modal and really interrupt the flow of input. Secondly, as you said - how do you know when the person has stopped "typing." Unless you use some sort of timing mechanism (which is more trouble than it's worth), you don't. My suggestion would be to utilize a "div" within your HTML that shows there is an error UNTIL you reach 10 characters. Once that happens, you can hide the div. (And, of course, the div can be styled to look pretty in the meantime.)
So...how to do this...
Let's assuming your input field has an id of "myField." If you are using jQuery (which is in your tags), you would do something like this.
$(function() {
var keypresses = 0;
$('#myField').keyUp(function () {
keypresses++;
if(keypresses == 10) {
$('#error').hide(); // This is your div error with some error text in it.
// Do other stuff.
} else {
// Display an error.
}
});
Alternatively, if you don't want to use the keypresses variable, you can also use..
if($(this).val().length == 10) { }
The real issue is the fact that you are measuring in key press events, because not all key presses (even when the field has focus) will insert a character into field (for example returnesc). Therefore, you will need to measure the string length in order to validate the code before you start executing functions.
In actuality you don't even need jQuery to accomplish what you need, just bind the function call to a key press event, and only execute the function call if yourstring.length = 10
yourInput.onKeyPress(yourString.length = 10 && yourFunction());
Try -
$('#idofinputfield').keyUp(function () {
var length = $('#idofinputfield').val().length;
if(length <= 10){
alert("less than 10");
}else{
alert("greaterthan 10");
}
});
Is there a way to limit a form input field to be between certain number range, say (0,100)
I'm filtering the input in the onkeydown event, to accept only numbers, the problem
is I want to reject a number if that number would make the input to go out of range
So I need a way to see if the current value of the input plus the key the user is pressing
will sum up between the range.
I tried using:
if((parseFloat(this.value) + parseFloat(String.fromCharCode(e.keyCode)) > 100){
return false;
}
the thing is e.keyCode can return different codes for the same number, right now is returning 57 for the
number 9, but 105 if i press the number on the numpad.
Is there a way to accomplish this?
Personally, I would just check it when the field loses focus (or when the form is submitted). Popping up errors as the user is typing (or preventing their keystrokes from registering in the field) is usually just going to annoy them.
And of course you probably knew this already, but make sure you check the value on the server side after the form is submitted as well. Never rely on javascript validation!
Trying to anticipate what the resulting value is going to be is harder than you think. Remember the user might be pressing backspace, or the cursor might not be at the end of the field, or the user might have part of the value selected, to be replaced on next keypress, and so on. It's also possible to manipulate the text field through mouse operations you won't get any say in.
The traditional approach is to put your validation on the ‘keyup’ event instead of ‘keypress’. Then you get the full, post-change value of the field. You don't get the chance to deny the keypress, but you can reset the field to the last-known-good value instead.
But either way it's best not to try to constrain input too tightly, because this can make it terribly difficult to type. For example, “12.” is an invalid number you might want to deny... but if you did, it would become very difficult to type “12.3”! Better to allow any input, but signal when the current input is out of bounds, by some mechanism (eg. turning the text red is common).
Adding the current value plus the float value of the character typed is not what you want. Think about if the current value is 99.0 and the user types a "5", the actual value is 99.05 but your expression would evaluate to 104.0. You need to append the key character to the current value before parsing anything into a float.
As for the key code, here is a reference to the javascript key codes. Using that you could write your own function like this:
function fromKeyCode(code) {
var asciiCode = code;
if (code > 95 && code < 106) {
asciiCode -= 48;
}
return String.fromCharCode(asciiCode);
}
var total = new Number(20.00);
alert(total.toFixed(2));
That will allow you to set a fixed width on the precision of 2 decimal places. In this case I am making sure with a js required field check that money only has 2 spots after the 2.
I'm not sure if I understand your question fully, but check the Number() methods, there has to be something there to help you.
You can catch the input on keyup, after the value contains the new input.
Then just look at the value-
inputelement.onkeyup= function(e){
e= window.event? event.srcElement: e.target;
var val= parseFloat(e.value) || 0;
e.value= Math.max(0, Math.min(100, val));
}