Why it is not entering in if condition - javascript

<script type="text/javascript">
//var EProductId = prompt('Please enter your product Id');
var EProductId = [];
EProductId[0] = prompt("New member name?");
//Product price, code, name, declare here
var ProductId = [];
ProductId[0] = 001;
var product = [];
product[0] = "tshirt";
var ProdPrice = [];
ProdPrice[0] = 299;
//Condition start here
if (ProductId[0] === EProductId[0]) {
// var EProductId2 = parseInt(prompt("Please enter a product", "")ProductId[0] + ' ' + product[0] + ' ' + ProdPrice[0]);
prompt(ProductId[0] + ' ' + product[0] + ' ' + ProdPrice[0]);
} else{
alert("You pressed Cancel or no value was entered!");
}
</script>
Why it is not entering in if condition. i am entering the value 001 after run a program but it alert the message is You pressed Cancel or no value was entered!

if (ProductId[0] == EProductId[0]) {}
Only use === when comparing types.

=== is only used for strict comparisons in javascript. For example: if('0' == 0) would return true as only values are compared here. However, === would check if they are of the same type (2 strings, 2 numbers, but not 1 of each). So, 0===0 returns true while 0==='0' returns false.
You should use == instead. Using == you can compare if values of different types are 'truthy' or 'falsy'. Example: 0 == 0 returns true as well as '0' == 0.

typeof(prompt()) returns string. You will have to convert it to an integer first using parseInt(string, radix). The 10 specifies base 10, the common numbering system used by people.
if (ProductId[0] === parseInt(EProductId[0],10))

I guess it returns "001" as a string, try this
if (ProductId[0] === +EProductId[0])

Related

Price calculation based on dimensions in WooCommerce single product page

Based on "Get selected variation price in jQuery on Woocommerce Variable products" answer code, in my code bellow, I have a problem with the price calculation of a WooCommerce variable product.
The price gets multiplied with 10 or 1000, depending on the option selected on a dropdown, which is not supposed to happen and I don't know why it is happening.
Here is my code:
<script>
jQuery(function($) {
var jsonData = <?php echo json_encode($variations_data); ?>,
inputVID = 'input.variation_id';
$('input').change( function(){
if( '' != $(inputVID).val() ) {
var vid = $(inputVID).val(), // VARIATION ID
length = $('#cfwc-title-field').val(), // LENGTH
diameter = $('#diameter').val(), // DIAMETER
ene_enden = $('#id_dropdown_one_end').find('option:selected').attr("value_one_end"),
vprice = ''; // Initilizing
// Loop through variation IDs / Prices pairs
$.each( jsonData, function( index, price ) {
if( index == $(inputVID).val() ) {
vprice = price; // The right variation price
}
});
var rope_price = (length*vprice) + ene_enden;
if (rope_price != 0){
$('.price').html(rope_price+',-');
}
alert('variation Id: '+vid+' || Lengde: '+length+' || Diameter: '+diameter+' || Variantpris: '+vprice+ ' || Rope price: '+rope_price+' || ene_enden = '+ene_enden);
}
});
});
</script>
For some reason rope_price gets multiplied by 10 or concatenated with 0 when the option selected for 'I enden av tauet ' is 'Ingenting'(it's value is 0). When I change the option selected to any of the others rope_price gets multiplied with 1000 or concatenated with 00. I don't know why this is happening.
Any ideas?
Because you are concatenating strings. Is not the same 1 + 0 than "1" + "0", as you can check here:
console.log("1 + 0 =", 1 + 0);
console.log('"1" + "0" =', "1" + "0");
When you get a value from an HTML object, you receive it as a string. If you want to use it as a number you must convert it before. You can use either Number or parseFloat (even parseInt, but will remove decimals).
var oneNumber = 1;
var oneString = "1";
var oneConverted = Number(oneString);
console.log("typeof oneNumber:", typeof oneNumber);
console.log("typeof oneString:", typeof oneString);
console.log("typeof oneConverted:", typeof oneConverted);
console.log("oneNumber + oneNumber =", oneNumber + oneNumber);
console.log('oneString + oneString =', oneString + oneString);
console.log('oneConverted + oneConverted =', oneConverted + oneConverted);
The exact problem you are having is your ene_enden variable being a string in the line var rope_price = (length*vprice) + ene_enden;. When you multiply two strings, they are automatically converted to a number (your (length*vprice)), but when you concatenate that number to another string, they are converted automatically to a string again (your + ene_enden), so you must first convert ene_enden to a number, ot better convert all expected number variables to a number.

How can I replace certain data strings with predefined data using Javascript?

I would like to use JavaScript to take data entered into a text field and replace the first two digits with a character and at the same time preserve the remaining digits in the string. The input data will always be 6 digits in length and there are 4 different possible character options depending on the first 2 digits of the input data. Here are the four possible options.
00 = A, 01 = M, 31 = B, 71 = F
So for example, if the input data is 001234, the output would need to be A1234. If the input is 719999, the output needs to be F9999.
I appreciate any help you can provide and thank you in advance for your support.
You declare tc_event; I assume this is a value returned by another function or application. But in your function you call TC_event. Please bare in mind that variables in JS are case sensitive. So tc_event is an entirely different variable than TC_event.
In your function you don't assing the returned value of strNewFld to tc_event so even while returned, tc_event will remain the initial value.
var persNr = "711212";
var strSrc = persNr ;
var strLtr = strSrc.substring(0,2);
var strNum = strSrc.substr(2,4);
console.log("This is strLtr: " + strLtr);
console.log("This is strNum: " + strNum);
var strNewFld = "";
var strLtrOut= "";
// In your if statement you use a single =. This means assign.
// To compare allways use ==. This compares.
if (strLtr == "00"){
strLtrOut = "A";
}
if (strLtr == "01"){
strLtrOut = "M";
}
if (strLtr == "31"){
strLtrOut = "B";
}
if (strLtr == "71"){
strLtrOut = "F";
}
strNewFld = strLtrOut + strNum;
// here you could assign value of strNewFld
// to tc_event or directly assiging
// strLtrOut + strNum to tc_event.
tc_event = strLtrOut + strNum
console.log("This is strNewFld: " + strNewFld);
I put it in a Snippet for you to understand what your variables do and how to manipulate it with if statements. A Switch statement should be more suitable. You can ask if needed.
var persNr = "021212"
var strLtr = persNr.substring(0,2);
var strNum = persNr.substr(2,4);
if (strLtr == "01"){
strLtrOut = "A" + strNum ;
}
if (strLtr == "02"){
strLtrOut = "B" + strNum ;
}
console.log("This is strLtr: " + strLtr);
console.log("This is strNum: " + strNum);
console.log("This is strLtrOut: " + strLtrOut);

How to deal with "undefined" and "NaN" in simple javascript calculations?

So two dropdowns and a few javascript functions to choose a price and set a country (which comes with a tax rate). Then display the price + tax rate = total to the user on the payment form.
If a price and a country(tax rate) are selected, the javascript and the sums work, thusly:
£49.99 + 10% VAT = £54.99
If a price but no country(tax rate) are selected, this happens:
Total: £49.99 + undefined% VAT = £NaN
And if neither a price or a country(tax rate) are selected, then we get:
£undefined + undefined% VAT = £NaN
So the question is: how do we deal with those ugly errors from javascript? What's the javascript way to deal with if/else for undefined and NaN?
Thanks.
UPDATE 2: the NaN check works, but where do I put the undefined check. Have added the TaxPrice function so you can see where it is coming from.
// First grab the tax rate from a drop down
function TaxPrice()
{
var taxprice=0;
var theForm = document.forms["payment-form"];
var selectedrate = theForm.elements["country_vat"];
taxprice = tax_rates[selectedrate.value];
return taxprice;
}
// Then calculate the total, including the NaN checks
function calculateTotal()
{
var TaxRate = TaxPrice() / 100;
var TotalPrice = PlanPrice() + (TaxRate * PlanPrice());
var TotalTax = (TaxRate * PlanPrice())
if(isNaN(TotalPrice)) {
// check NaN
TotalPrice = 0
}
if(isNaN(TotalTax)) {
// check NaN
TotalTax = 0
}
//display the price
var divobj = document.getElementById('p');
divobj.innerHTML = "£" + PlanPrice();
//display the tax rate
var divobj = document.getElementById('r');
divobj.innerHTML = "£" + TotalTax.toFixed(2) + " (" + TaxPrice() + "% VAT)";
//display the total
var divobj = document.getElementById('t');
divobj.innerHTML = "£" + TotalPrice.toFixed(2);
}
Check specifically for undefined with
if(typeof price === "undefined"){}
Check specifically for NaN with
if(isNaN(price)){}
Generally you can also simply do
if(price){}
Where the inside of the if statement will return false if price is NaN, undefined or null, but also when it is 0 or empty string, which you may not want so you'd need to specify it in the condition.
Specifically in your case, it would be good not to perform the calculations when either of its parts is not defined as the result will only create undefined or NaN values anyway:
function calculateTotal(){
//first check all you need for the calculation is defined
if (typeof TaxPrice() != 'undefined' && typeof PlanPrice() != 'undefined'){
//perform the calculation and output the result
}else{
//output an error message or a default ouput
}
}
Then you don't have to check for NaN's because those were caused by making arithmetics with undefined's.
Please covert value to a finite number, for example:
function toNumber(value) {
if(typeof value !== 'number') {
// covert type to number
// void 0, null, true, false, 'abc', [], {} => NaN
// [0] => 0
value = parseFloat(value)
}
if(isNaN(value)) {
// check NaN
value = 0
}
if(!isFinite(value)) {
// check Infinity and -Infinity
value = Number.MAX_SAFE_INTEGER * Math.sign(value)
}
return value
}
make a function similar to this
function get_value(input, default_value) {
return input === undefined || isNaN(input) ? default_value : input;
}
and then use it whenever you need to do calculations with a possible undefined value. Eg
var a = 10;
var sum = a + get_value(b, 0); // b is undefined and get_Value returns 0, sum is 10
var prod = a * get_value(b, 1); // b is undefined and get_Value returns 1, prod is 10
Use the isNaN() function to check if a variable is NaN.
e.g. see here: http://www.w3schools.com/jsref/jsref_isnan.asp
You could also track which vars were set in additional vars. ;)
If you want calculation to be done only when both of them are selected, then simply check for these errors in front of your code by:
if(typeof (your_price_variable) !== undefined && typeof (your_country_variable) !== undefined)
and make the function only run when this condition is met. Then the output won't be "NaN."

I'm trying to find the highest mark and lowest mark in an array with prompts

So my teacher assigned us an assignment to make a program to find the highest and lowest mark of a maximum of 15 students. So it's possible to put in less than 15 students. The user must input the student's name and after the student's mark. After all the student's names and marks have entered, it's suppose to compare the marks to find the least and the greatest.
CODE:
var Students = ["sn1", "sn2", "sn3", "sn4", "sn5", "sn6", "sn7", "sn8", "sn9", "sn10", "sn11", "sn12", "sn13", "sn14", "sn15"]; //student's name array
var Marks = ["sm1", "sm2", "sm3", "sm4", "sm5", "sm6", "sm7", "sm8", "sm9", "sm10", "sm11", "sm12", "sm13", "sm14", "sm15"]; //student's marks array
Students[0] = prompt("Student 1's name.");
if(Students[0].length == 0) {
Marks[0] = null
} else {
Marks[0] = prompt("Student 1's mark."); //I just copied and pasted this 15 times and changed the [0] to the next number.
while(isNaN(Marks[0]) || Marks[0] >= 101 || Marks[0] <= -101) { //if number is greater than or equal to 101, or less than or equal to -1. Prevents a mark higher than 100 and less than 0.
window.alert("Please input a number between 0-100.");
Marks[0] = 0
Marks[0] = prompt("Student 1's mark."); //reprompt.
}
}
console.log(Students[0] + " " + Marks[0]); //displays mark.
var greatest = -100; //my friend did this part so I don't know if it's right.
var least = 100;
var trackg = 0;
var trackl = 0;
if (Marks[x] != null){ //if this isn't here then I get an error with null.length can't be measured below.
for(var x = 0; x < Marks.length; x ++) {
if(Marks[x].length == 2) {
" " + Marks[x];
}
if(Marks[x] >= greatest && Marks[x] != null) {
greatest = Marks[x]
trackg = x
}
}
}
for(var j = 0; j < Marks.length; j ++) { //the marks[x] != null doesn't work here. it will show that the greatest number is the least number as well which it isn't.
if (Marks[j] <= least && Marks[j] != null){
least = Marks[j];
trackl = j;
}
}
console.log(Students[trackg] + " has the highest mark of " + Marks[trackg] + ". " + Students[trackl] + " has the lowest mark of " + Marks[trackl] + ".");
PROBLEMS:
1. When it compares the number it just takes the first number as the largest number and that's it. So lets say I put the first student's mark as 99 and after I put the 2nd student's as 100. It says 99 is the highest mark and same with negatives for the lowest.
2.I also get that if I put in 100, numbers like 29, 99, etc are higher numbers due to 1 < 2 or 9 etc.
3.For negative numbers, If I put -13 and -99, -13 says it's the lowest which it isn't.
Also, if I put in 10 and 100 (even as negatives), 10 is greater/ the least.
I've tried so many things and I don't know whats wrong. (Btw this is my first time with javascript). This assignments due Monday. Thanks ;A;
This is an example of how you could do it. Note how the validation is done, and conversion of user input to an actual number for comparison. Only one main loop is necessary; the while loops are to ensure the user enters valid data.
You do not need to actually store all the students' data as an array to display the highest and lowest result.
var students = [];
var numOfStudents, highest = { mark:-1 }, lowest = { mark:101 };
// Get number of students between 1 and 15
while (isNaN(numOfStudents) || numOfStudents <= 0 || numOfStudents > 15)
numOfStudents = parseInt(prompt('How many students? (1-15)', '1'), 10);
// For each student, get the name and mark
for (i = 1; i <= numOfStudents; i++) {
var student = {};
while (typeof student.name === 'undefined' || student.name == '')
student.name = prompt('Enter Student '+i+' name:', '');
while (typeof student.mark === 'undefined' || isNaN(student.mark) || student.mark < 0 || student.mark > 100)
student.mark = parseFloat(prompt('Enter Student '+i+' mark (0-100):', ''));
// Check if highest or lowest
if(student.mark > highest.mark) highest = student;
if(student.mark < lowest.mark) lowest = student;
// Save current student to the list (optional)
students.push(student);
}
// Display result
document.body.innerHTML = highest.name + " has the highest mark of " + highest.mark + ". " + lowest.name + " has the lowest mark of " + lowest.mark + ".";

Javascript Operators Issue working with Decimals

I got everything almost where I want it. My only problem is that for some reason I can't get the bctf1 to add right. Say if bctf = 10, the result with the code would be 100.59 instead of 10.59. Say if bctf = 25, the result with the code would be $251.03 instead of 26.03.
// BUY TOTAL
<script type="text/javascript">
function buytot(){
var bctf = document.getElementById('buyctf').value;
if(bctf.charAt(0) == "0" || bctf.charAt(0) == "" || bctf.charAt(0) == " "){
bctf2 = "0.00";
} else {
pcbctf = bctf*.029;
pcplusc = pcbctf+.30;
bctf1 = bctf+pcplusc;
bctf2 = Math.round(bctf1*100)/100;
}
document.getElementById('buyctotal').innerHTML = bctf2;
}
</script>
Here's the HTML with JS -> http://jsfiddle.net/hhWDe/5/
Force a data type on this:
var bctf = parseFloat(document.getElementById('buyctf').value);
You need to convert the String values returned by the element value properties into numbers. Something like this:
var bctf = Number(document.getElementById('buyctf').value);
// OR
var bctf = parseFloat(document.getElementById('buyctf').value, 10);
Also, consider using the "toFixed" number method to get the ".00 decimal places for whole dollar amounts:
var oneDollar = 1;
oneDollar; // => 1
oneDollar.toFixed(2); // => "1.00"
You can add "+" to convert a value to an integer (or float).
It will take any string and convert it, if the string cannot be converted, it will return NaN:
So your script would look like the following:
var bcft = +document.getElementByID('buyctf').value;
Thank You all :) This is the working code. I add bctf0 = Number(document.getElementById('buyctf').value); after the else and everything worked fine.
// BUY TOTAL
function buytot(){
var bctf = document.getElementById('buyctf').value;
if(bctf.charAt(0) == "0" || bctf.charAt(0) == "" || bctf.charAt(0) == " "){ bctf2 = "0.00";
} else {
bctf0 = Number(document.getElementById('buyctf').value);
pcbctf = bctf0*.029;
pcplusc = pcbctf+.30;
bctf1 = bctf0+pcplusc;
bctf2 = Math.round(bctf1*100)/100;
}
document.getElementById('buyctotal').innerHTML = bctf2;
}

Categories