jQuery won't count up variables - javascript

I have a little problem with my jQuery script: instead of counting up all variables, the script puts them next to each other. How do I count up the variables? (I am new to jQuery, so maybe I overlooked something or made a stupid mistake).
This is the line of code that should count up the variables.
totalcost = ((commissioncost + paypalcost) + qrticketcost);
http://jsfiddle.net/bsuh5q8k/1/
Thanks.

Often when you retrieve a value from a field using jquery's .val(), you'll get the string value (String type) instead of the numeric value you desire here. For instance, the field value may be 37.50, but you're getting "37.50" from .val()
So when you do this:
commissioncost = $('input[name=price]').val();
You'll get the String value.
So instead, try this:
commissioncost = Number($('input[name=price]').val());
This will convert/cast the value into a Number for you.
Also, a word of caution: just be sure whatever value is in that field, it can be evaluated as a Number, otherwise comissioncost will equal "NaN" (not a number) and will give you the same grief you're experiencing now. The rudimentary method to check if the type conversion was successful is:
commissioncost = Number($('input[name=price]').val());
if(isNaN(commissioncost)){
// oops, value wasn't a number!
}else{
// hooray! value was a number (most of the time - but that's a longer discussion)
}

commissioncost is being treated as a string. So when you add it thinks you're wanting to concatenate.
When you pull it from the input, explicitly tell Javascript that it's a number/float.
commissioncost = parseFloat($('input[name=price]').val());

Related

Why do I get undefined here?

function myFunc() {
var word = document.getElementById("Text1").value;
var num = parseInt(document.getElementById("Text2").value);
var numstr = num.split(",");
var wordstr = word.split("");
for (i = 0; i < word.length; i++) {
}
document.getElementById("myDiv").innerHTML += (wordstr[(numstr[i])-1]);
}
did I parseInt incorrectly? I've tried toString(), with ParseInt it doesn't do anything and without it I get 'undefined'
The parseInt() function parses a string and returns an integer.
You check your input with id "Text2" and show your HTML here to clearify the issue.
Without knowing more about your problem, it looks like you are misunderstanding how parseInt() works. Despite the misleading name, it will read your string character by character, attempting to create an integer. It will stop as soon as it finds a character that can't be part of an integer.
If you pass it "1,2,3,4" then it will read the 2 fine, but as a comma cannot be parsed as part of an integer, it will return the number 2. It doesn't make sense to call split on a number.
As others have said, you really need to give us more details for us to be able to help, but I suspect a large part of the problem is not understanding what some of these functions do.
Maybe you could explain what you're trying to achieve, then we can help you get there. Right now, your code isn't clear enough without extra information.

What is the best / suggested method to input more than 1 parameter (*val) through Annyang speech recognition library?

Annyang command uses a *val to input values to the callback function. What should I do if I want to input more than one item ?
For example, I want to update a form based on user input. So I could have a command like
set Name *val
then val would contain the Name value that I could then assign to the field. But if my form has lot of fields writing a command like this for all fields could be tedious. Instead, I could have
set *FieldName *FieldVal
This command, would return two parameters instead FieldName and FieldVal. If FieldName is valid name of available fields on the page, then I could update the value with FieldVal, or ignore the command.
One way to achieve this, is, ofcourse parse the val to first get the FieldName and then FieldVal from a command like
set *val
but I dont think it would always result in clean solutions.
is there a suggested method to achieve this ?
What you are looking for is not the "splat" operator (*) but the "named-variable" operator (:).
Your command will then look like
var commands = {
'set :FormId with :Value':setForms,
}
annyang.addCommands(commands);
function setForm(formId, value){
if(isValidForm(formId)){
forms[formId].value = value;
}
}
And now saying "Set foo with bar" will set the forms["foo"]'s value to "bar".

javascript variables always not equal

I have two variables, totalGuess and condensedAnswer. I am creating a jQuery click event and if totalGuess doesn't equal condensedAnswer then the click event will not occur and a div called message will display the message "Sorry, but your answer is incorrect. Please try again."
The problem is, totalGuess in the if statement is never equal to condensedAnswer. I've tried seeing typeof and they are both strings. I've tried console.log(totalGuess+"\n"+condensedAnswer); and they both return the same value. I've tried hardcoding the condensedAnswer, and totalGuess was able to be equal to the hardcoded answer. But when I tried comparing condensedAnswer with the hardcoded answer, it's not equal, even though the console.log value for condensedAnswer is the same. I'm not what's wrong.
Here's the code snippet:
$('.submitGuess').click(function(e){
var totalGuess = "";
var condensedAnswer = answer.replace(new RegExp(" ","g"), "");
$('.crypto-input').each(function(){
totalGuess += $(this).val();
});
// if incorrect guess
if(totalGuess !== condensedAnswer) {
$('.message').text("Sorry, but your answer is incorrect. Please try again.");
e.preventDefault();
}
// if user wins, congratulate them and submit the form
else {
return true;
}
});
If it helps, here's the page, just a random test cryptogram plugin for Wordpress:
http://playfuldevotions.com/archives/140
The problem has nothing to do with the check. The problem is the fact your value you are checking against has hidden characters. However you are getting that string has the issue.
Simple debugging shows the problem
> escape(totalGuess)
"God%27sMasterpieceMatthew15%3A99Psalms129%3A158"
> escape(condensedAnswer)
"God%27sMasterpieceMatthew15%3A99Psalms129%3A158%00"
It has a null character at the end.
Now looking at how you fill in the answer you have an array with numbers
"071,111,100,039,...49,053,056,"
Look at the end we have a trailing comma
when you do a split that means the last index of your array is going to be "" and hence why you get a null.
Remove the trailing comma and it will magically work.

Javascript document.getElementsByName() function is being weird at me

I've got the following variables in my simple javascript calculator:
var distance = parseInt(document.getElementsByName("distance"), 10);
var mins_running = parseInt(document.getElementsByName("mins_running").value, 10); // the running pace minutes
var secs_running = parseInt(document.getElementsByName("secs_running").value, 10); // the running pace seconds
var mins_walking = parseInt(document.getElementsByName("mins_walking").value, 10); // the walking pace minutes
var secs_walking = parseInt(document.getElementsByName("secs_walking").value, 10); // the walking pace seconds
The problem is, when I try to use these variables (entered as text from a form but meant to be used as numbers in the calculator). When I do a typeof() in the developer console.log I'm told the values are of type 'number', but the very next line is also a console.log('mins_running'), for example, and it explicitly states the value is "NaN". Is my value a number or not? What's going on? Stupid javascript--be more normal, darn it!
Any reasonable input/help will be appreciated.
Thanks for all the help, guys. Looks like I'm back to using the old Form.elementName.value thing instead. (if this is a really bad idea or just not good for production code at all, please feel free to say something.)
document.getElementsByName("mins_running")
returns a NodeList, which has no attribute value. Use
document.getElementsByName("mins_running")[0].value
instead.
Example:
HTML:
<input type="text" name="mins_running" value="10">
<br><button id="theButton">Click Me</button>
JavaScript:
document.getElementById("theButton").onclick = function() {
// Note we're getting the first match ----------------vvv
var field = document.getElementsByName("mins_running")[0];
display("The field's current value is: " +
parseInt(field.value, 10));
// And using its value-^^^^^
};
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
Live Copy | Source
Waleed shared how to fix it.
The technical reason why you got NaN there is...
You grab a reference to a NodeList with document.getElementsByName("distance"), and you attempt to access the property value on that. That property does not exist on NodeList, or anywhere on the prototype chain. In JavaScript, that means undefined is returned.
When you call parseInt() with undefined as the first argument, the function will toString() it and return "undefined". You explicitly set the base as 10, which obviously only covers digits 0 to 9, and the number can't be parsed. When this happens, parseInt() returns NaN. Since NaN is of the Number type (it's part of the IEEE-754 specification), the typeof operator tells you it's a "Number".
If you'd set the base as 31, it'd be able to parse "undefined", and it'd be 26231474015353 :)
Set ids for your tags and use getElementById instead.

Javascript set attribute using variable

I'm unsure of the syntax here, but the code I have so far is this... (Note: I am passing the id's of three textboxes in the form '#begmile','#endmile','#totmile', and I want to set the value of the 'totmile' checkbox to endmile-bigmile)
function subtract(begmile, endmile, totmile){
y=$(begmile).attr('value');
z=$(endmile).attr('value');
y=z-y;
$(totmile).setAttr('value',???);
}
I'm not sure if my syntax here so far is correct, but assuming it is (that y is properly set to endmile-begmile, how do I use setAttr to set the value of totmile to the value of y?
This is the correct syntax:
var href = 'http://cnn.com';
$(selector).attr('href', href);
your last line isn't calling the right method:
$(totmile).setAttr('value',???);
should be:
$(totmile).attr('value',???);
e.g.
$(totmile).attr('value', y);//set the value to the variable "y"
you can also call .val(); instead to easily get the value of a field, or .val(newValue); to set the value.
also note that if your values for "y" and "z" are not actually representing numbers you'll get a weird result.
The value attribute refers to the default value for the textbox, not the current one. The current one is stored in the value property.
function subtract(begmile, endmile, totmile) {
document.getElementById(totmile).value =
document.getElementById(endmile).value - document.getElementById(begmile).value;
}
This also removes the need for jQuery, since the JavaScript Sledgehammer is far too excessive for this job. To make sure it works, just remove the # when you pass IDs to the function.

Categories