I'm trying to find whether or a not a number is a perfect number, but I can't get it to print right. The numbers 6, 496, 8128 are perfect numbers but when I entered those it kept printing from var res2 instead of var res1. What's the problem here, can anyone can help?
function perfectNo(number) {
var temp = 0;
var res1 = "It is a perfect number";
var res2 = "It is not a perfect number";
for (var i = 1; i <= number / 2; i++) {
if (number % i == 0) {
temp += i;
}
}
if (temp == number && temp != 0) {
document.getElementById("results").innerHTML = res1;
} else {
document.getElementById("results").innerHTML = res2;
}
}
<input id="num">
<input type="button" onclick="perfectNo()" value="check">
<br>
<p>Answer:</p>
<p id="results"></p>
<br>
Try with :
var number = document.getElementById("num").value;
Like this :
function perfectNo() {
var number = document.getElementById("num").value;
console.log(number);
var temp = 0;
var res1 = "It is a perfect number";
var res2 = "It is not a perfect number";
for (var i = 1; i <= number / 2; i++) {
if (number % i == 0) {
temp += i;
}
}
if (temp == number && temp != 0) {
document.getElementById("results").innerHTML = res1;
} else {
document.getElementById("results").innerHTML = res2;
}
}
<input id="num">
<input type="button" onclick="perfectNo()" value="check">
<br>
<p>Answer:</p>
<p id="results"></p>
<br>
Related
This is quite a lengthy code, but i wish to have the user put in her inputs but is limited to 5 tries. Each time she enters a wrong number, it is being stored into an array. At the end of her 5 tries, all her guesses will be displayed in the text area that is created. Idk why my loop isn't working & i'm currently am unsure of loops for javascript. Help would be appreciated :) Run the code would help you better understand what I mean!
var randomNo;
function getRandomArbitrary(min, max)
{
return Math.random() * (max - min) + min;
}
function playFunction()
{
const message1 = document.getElementById("wrongInput");
const message2 = document.getElementById("wrongInput2");
var min = Number(document.getElementById("input").value);
var max = Number(document.getElementById("input2").value);
function inIt()
{
message2.innerHTML = "";
message1.innerHTML = "";
}
function validateInput(displayErrorElement, value)
{
let message;
if (value = "")
{
message = "empty";
} else if (isNaN(value))
{
message = "not a number";
}
if (message)
{
displayErrorElement.innerHTML = "Input is " + message;
displayErrorElement.style.color = "red";
return false;
}
return true;
}
function validateRange(displayErrorElement, min, max)
{
if (min > max)
{
displayErrorElement.innerHTML = "The input must be higher than the lowest number";
return false;
}
return true;
}
inIt();
if(!validateInput(message1, min)) return false;
if(!validateInput(message2, max)) return false;
if(!validateRange(message2, min, max)) return false;
console.log(min);
console.log(max);
randomNo = Math.floor(getRandomArbitrary(max, min));
console.log(randomNo);
console.log(randomNo);
}
values = [];
function guess()
{
var maxGuesses = 5;
var x;
var target;
for (let i = 0; i < 5; i++)
{
var guess = document.getElementById("guessField").value;
//output the msg
var output = document.getElementById("output");
if (guess == randomNo)
{
output.value = "You have guessed correctly! " + "(" + guess + ")";
return true;
}
else if (guess > randomNo)
{
output.value = "Number is too high! " + "(" + guess + ")";
return false;
} else {
output.value = "Number is too low! " + "(" + guess + ")";
return false;
}
if (x == 4)
{
output.value = "You have run out of tries!"
}
target = document.getElementById("output");
target.innerHTML = "The target number is " + randomNo;
x = document.getElementById("guessField");
values.push(x.value);
x.value = "";
}
}
function displayRecord()
{
document.getElementById("output").innerHTML = values.join("<br>");
}
Enter a smaller number<br>
<input id="input" type="text">
<span id="wrongInput"></span><br>
Enter a larger number<br>
<input id="input2" type="text">
<span id="wrongInput2"></span><br>
<button type="button" onclick="playFunction()">Play button</button>
<br>
<!-- guess the number -->
<label for="guess">Guess the number</label><br>
<input text="text" class="guessField" id="guessField">
<span id="guessMessage"></span>
<input type="button" onclick="guess()" value="Guess button"><br>
<p>Output area</p>
<textarea id="output" name="output" rows="5" style="width: 50%"></textarea>
The guess function should not have a loop. Since you add the guess to the values array, you can use that to keep track of how many guesses have been made and quit the game when values.length == 5;
Also note I append the messages with +=. Example output.value += "You ....
let values = [];
var randomNo;
function getRandomArbitrary(min, max)
{
return Math.random() * (max - min) + min;
}
function playFunction()
{
const message1 = document.getElementById("wrongInput");
const message2 = document.getElementById("wrongInput2");
var min = Number(document.getElementById("input").value);
var max = Number(document.getElementById("input2").value);
function inIt()
{
message2.innerHTML = "";
message1.innerHTML = "";
values = [];
document.getElementById("output").value = "";
}
function validateInput(displayErrorElement, value)
{
let message;
if (value = "")
{
message = "empty";
} else if (isNaN(value))
{
message = "not a number";
}
if (message)
{
displayErrorElement.innerHTML = "Input is " + message;
displayErrorElement.style.color = "red";
return false;
}
return true;
}
function validateRange(displayErrorElement, min, max)
{
if (min > max)
{
displayErrorElement.innerHTML = "The input must be higher than the lowest number";
return false;
}
return true;
}
inIt();
if(!validateInput(message1, min)) return false;
if(!validateInput(message2, max)) return false;
if(!validateRange(message2, min, max)) return false;
console.log(min);
console.log(max);
randomNo = Math.floor(getRandomArbitrary(max, min));
console.log(randomNo);
console.log(randomNo);
}
function guess()
{
var maxGuesses = 5;
if (values.length >= maxGuesses) return false;
var guess = document.getElementById("guessField").value;
document.getElementById("guessField").value = "";
values.push(guess);
//output the msg
var output = document.getElementById("output");
if (guess == randomNo) {
output.value += "You have guessed correctly! (" + guess + ")\n";
return true;
}
if (guess > randomNo)
{
output.value += "Number is too high! (" + guess + ")\n";
}
else {
output.value += "Number is too low! (" + guess + ")\n";
}
if (values.length == 5)
{
output.value += "You have run out of tries!\n"
output.value += "The target number is " + randomNo;
}
}
function displayRecord()
{
document.getElementById("output").innerHTML = values.join("<br>");
}
Enter a smaller number<br>
<input id="input" type="text">
<span id="wrongInput"></span><br>
Enter a larger number<br>
<input id="input2" type="text">
<span id="wrongInput2"></span><br>
<button type="button" onclick="playFunction()">Play button</button>
<br>
<!-- guess the number -->
<label for="guess">Guess the number</label><br>
<input text="text" class="guessField" id="guessField">
<span id="guessMessage"></span>
<input type="button" onclick="guess()" value="Guess button"><br>
<p>Output area</p>
<textarea id="output" name="output" rows="5" style="width: 50%"></textarea>
My mortgage calculator includes a down payment field for either a value or a percentage.
If the user enters a value, the percentage is calculated and displayed. If the user enters a percentage, the value is calculated and displayed.
The problem I am having is that once entered, only the value can be modified, not the percentage.
The relevant code is
var Vdown = document.calc.downPayment.value;
if (Vdown == 0 || Vdown == "") {
Vdown = 0;
} else {
var result = (Vdown / VappraisedValue) * 100;
document.calc.downPaymentPercent.value = result;
document.calc.downPayment.value = Vdown;
}
var VdownPercent = document.calc.downPaymentPercent.value;
if (VdownPercent == 0 || VdownPercent == "") {
VdownPercent = 0;
} else {
var percent = (VdownPercent / 100) * VappraisedValue;
document.calc.downPayment.value = percent.toFixed(0);
document.calc.downPaymentPercent.value = VdownPercent;
}
Please see my jsfiddle
function fn(num, places, comma) {
var isNeg = 0;
if (num < 0) {
num = num * -1;
isNeg = 1;
}
var myDecFact = 1;
var myPlaces = 0;
var myZeros = "";
while (myPlaces < places) {
myDecFact = myDecFact * 10;
myPlaces = Number(myPlaces) + Number(1);
myZeros = myZeros + "0";
}
onum = Math.round(num * myDecFact) / myDecFact;
integer = Math.floor(onum);
if (Math.ceil(onum) == integer) {
decimal = myZeros;
} else {
decimal = Math.round((onum - integer) * myDecFact)
}
decimal = decimal.toString();
if (decimal.length < places) {
fillZeroes = places - decimal.length;
for (z = 0; z < fillZeroes; z++) {
decimal = "0" + decimal;
}
}
if (places > 0) {
decimal = "." + decimal;
}
if (comma == 1) {
integer = integer.toString();
var tmpnum = "";
var tmpinteger = "";
var y = 0;
for (x = integer.length; x > 0; x--) {
tmpnum = tmpnum + integer.charAt(x - 1);
y = y + 1;
if (y == 3 & x > 1) {
tmpnum = tmpnum + ",";
y = 0;
}
}
for (x = tmpnum.length; x > 0; x--) {
tmpinteger = tmpinteger + tmpnum.charAt(x - 1);
}
finNum = tmpinteger + "" + decimal;
} else {
finNum = integer + "" + decimal;
}
if (isNeg == 1) {
finNum = "-" + finNum;
}
return finNum;
}
function sn(num) {
num = num.toString();
var len = num.length;
var rnum = "";
var test = "";
var j = 0;
var b = num.substring(0, 1);
if (b == "-") {
rnum = "-";
}
for (i = 0; i <= len; i++) {
b = num.substring(i, i + 1);
if (b == "0" || b == "1" || b == "2" || b == "3" || b == "4" || b == "5" || b == "6" || b == "7" || b == "8" || b == "9" || b == ".") {
rnum = rnum + "" + b;
}
}
if (rnum == "" || rnum == "-") {
rnum = 0;
}
rnum = Number(rnum);
return rnum;
}
function computeForm(form) {
var VappraisedValue = document.calc.appraisedValue.value;
var Vdown = document.calc.downPayment.value;
if (Vdown == 0 || Vdown == "") {
Vdown = 0;
} else {
var result = (Vdown / VappraisedValue) * 100;
document.calc.downPaymentPercent.value = result;
document.calc.downPayment.value = Vdown;
}
var VdownPercent = document.calc.downPaymentPercent.value;
if (VdownPercent == 0 || VdownPercent == "") {
VdownPercent = 0;
} else {
var percent = (VdownPercent / 100) * VappraisedValue;
document.calc.downPayment.value = percent.toFixed(0);
document.calc.downPaymentPercent.value = VdownPercent;
}
}
<form name="calc" method="post" action="#">
<table border='1' cellpadding='4' cellspacing='0'>
<tbody>
<tr>
<td nowrap>
Home value:
</td>
<td align="center">
<span class="input-group-addon">$</span>
<input id="appraised-value" type="number" min="0" max="10000000" step="25000" class="form-control" name="appraisedValue" onKeyUp="computeForm(this.form)" value="0" onfocus="if(this.value==this.defaultValue)this.value=''" onblur="if(this.value=='')this.value=this.defaultValue">
</td>
</tr>
<tr>
<td nowrap>
Down payment:
</td>
<td align="center">
<span class="input-group-addon">$</span>
<input id="down-payment" type="number" min="0" max="10000000" step="5000" class="form-control" name="downPayment" onKeyUp="computeForm(this.form)" value="0" onfocus="if(this.value==this.defaultValue)this.value=''">
<input id="down-payment-percent" type="number" min="0" max="100" step="1" class="form-control" name="downPaymentPercent" onKeyUp="computeForm(this.form)" value="0" onfocus="if(this.value==this.defaultValue)this.value=''">
<span class="input-group-addon">%</span>
</td>
</tr>
</tbody>
</table>
</form>
The issue is the way you are updating the Payment / Percent values - every time either value is updated, the code in computeForm uses the value in Payment to update Percent, and only then the value of Percent (just updated) is used to set Payment. As a result, whatever is in Payment will always win.
A couple of options to get it working the way you want it to:
You could pass a variable in the "onKeyUp" events of Payment and Percent that tells ComputeForm which to use to update the other, using an if(which === "pmt") { [code_to_update_payment] } else { [code_to_update_pct] } type construct.
You could break out the update code into two separate functions, function updatePmt() { } function updatePct() { } and then call each from the respective "onKeyUp" method in the HTML.
Either should work equally well to solve the behavior you are experiencing.
my main aim is to stop the program if the user guess the number 5 times OR when the user guess the correct answer, the program should end too.
function abc()
{
var guessbutton = document.getElementById("guessbutton");
var guess = document.getElementById("guess").value;
var maxtries = 5;
var count = 0;
var secret = 10;
while (count < 6)
{
if (guess == secret)
{
document.getElementById("feedback").innerHTML = "correct";
guessbutton.disabled=true;
break;
}
else if (guess > secret)
{
document.getElementById("feedback").innerHTML = "too high";
}
else if (guess < secret)
{
document.getElementById("feedback").innerHTML = "too low";
}
else
{document.getElementById("feedback").innerHTML = "max try";
guessbutton.disabled=true;
break;
}
count++;
}
}
the problem i am facing with this code is that it will continue even after 5 tries.
i am assuming the error is due to count++; not working correctly
this is my html code
<input id="guess" type="text" name="guess">
<button id="guessbutton" type="button" onclick="return abc()">Guess</button>
<p id="feedback"></p>
You need to get rid of the while loop. You are just looping without allowing the user to update the input textbox. You should be checking the count on every click.
var guessbutton = document.getElementById("guessbutton");
var count = 0;
var maxTries = 5;
var secret = 10;
function abc() {
var guess = Number(document.getElementById("guess").value);
count++;
console.log(count);
if (guess == secret) {
document.getElementById("feedback").innerHTML = "correct";
guessbutton.disabled = true;
} else if (guess > secret) {
document.getElementById("feedback").innerHTML = "too high";
} else if (guess < secret) {
document.getElementById("feedback").innerHTML = "too low";
}
if (count >= maxTries) {
document.getElementById("feedback").innerHTML = "max try";
guessbutton.disabled = true;
}
}
<input id="guess" type="text" name="guess">
<button id="guessbutton" type="button" onclick="return abc()">Guess</button>
<p id="feedback"></p>
I am trying to get javascript to format phone numbers based on a users input of 10 or 11 digits. The 11 digits are for phone numbers that start with a 1 at the beginning like a 1-800 number. I need the final output to be either 000-000-0000 or 1-000-000-0000. The sample javascript code that I was given to start out with, works with the 10 digit phone number but I need the javascript to also recognize if there is a 1800 number and append accordingly.
The following is my initial working javascript and below that is code I found online that addresses the 10 and 11 digital formatting however I don’t know how to mesh the two together.
Thank you in advance for any help given.
~~~~~~~~~~~~~~~~~
<script type="text/javascript">
var phoneNumberVars = [ "UserProfilePhone", "UserProfilePhone1", "UserProfilePhone2", "UserProfilePhone3", ];
InitialFormatTelephone();
function InitialFormatTelephone()
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
FormatTelephone(phoneNumberVars[i]);
}
}
function StorefrontEvaluateFieldsHook(field)
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
if (field.id == "FIELD_" + FieldIDs[phoneNumberVars[i]])
{
FormatTelephone(phoneNumberVars[i]);
}
}
}
function FormatTelephone(varName)
{
var num = document.getElementById("FIELD_" + FieldIDs[varName]).value;
var charArray = num.split("");
var digitCounter = 0;
var formattedNum;
if (charArray.length > 0)
formattedNum = “-“;
else
formattedNum = "";
var i;
for (i = 0;i < charArray.length; i++)
{
if (isDigit(charArray[i]))
{
formattedNum = formattedNum + charArray[i];
digitCounter++;
if (digitCounter == 3)
{
formattedNum = formattedNum + “-“;
}
if (digitCounter == 6)
{
formattedNum = formattedNum + "-";
}
}
}
if (digitCounter != 0 && digitCounter != 10)
{
alert ("Enter a valid phone number!");
}
// now that we have a formatted version of the user's phone number, replace the field with this new value
document.getElementById("FIELD_" + FieldIDs[varName]).value = formattedNum;
// force an update of the preview
PFSF_AjaxUpdateForm();
}
function isDigit(aChar)
{
myCharCode = aChar.charCodeAt(0);
if((myCharCode > 47) && (myCharCode < 58))
{
return true;
}
return false;
}
</script>
<script type="text/javascript">
var phoneNumberVars = [ "UserProfilePhone", "UserProfilePhone1", "UserProfilePhone2", "UserProfilePhone3", ];
InitialFormatTelephone();
function InitialFormatTelephone()
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
FormatTelephone(phoneNumberVars[i]);
}
}
function StorefrontEvaluateFieldsHook(field)
{
for (var i = 0; i < phoneNumberVars.length; i++)
{
if (field.id == "FIELD_" + FieldIDs[phoneNumberVars[i]])
{
FormatTelephone(phoneNumberVars[i]);
}
}
}
function FormatTelephone(varName)
{
var num = document.getElementById("FIELD_" + FieldIDs[varName]).value;
var cleanednum = num.replace( /[^0-9]/g, "");
var charArray = cleanednum.split("");
var digitCounter = 0;
var formattedNum = "";
var digitPos1 = 0;
var digitPos3 = 3;
var digitPos6 = 6;
if (charArray.length ===11)
{
digitPos1++;
digitPos3++;
digitPos6++;
}
if (charArray.length > 0)
formattedNum = "";
else
formattedNum = "";
var i;
for (i = 0;i < charArray.length; i++)
{
if (isDigit(charArray[i]))
{
formattedNum = formattedNum + charArray[i];
digitCounter++;
if (digitCounter === digitPos1)
{
formattedNum = formattedNum + "-";
}
if (digitCounter == digitPos3)
{
formattedNum = formattedNum + "-";
}
if (digitCounter == digitPos6)
{
formattedNum = formattedNum + "-";
}
}
}
if ((charArray.length ==10 || charArray.length == 11 || charArray.length == 0) === false)
{
alert ("Enter a valid phone number!");
}
// now that we have a formatted version of the user's phone number, replace the field with this new value
document.getElementById("FIELD_" + FieldIDs[varName]).value = formattedNum;
// force an update of the preview
PFSF_AjaxUpdateForm();
}
function isDigit(aChar)
{
myCharCode = aChar.charCodeAt(0);
if((myCharCode > 47) && (myCharCode < 58))
{
return true;
}
return false;
}
</script>
I wrote this code to validate credit card digits, saved it as an html file. It's not working though.
<html>
<head>
<script>
function mod10_check(val){
var nondigits = new RegExp(/[^0-9]+/g);
var number = val.replace(nondigits,'');
var pos, digit, i, sub_total, sum = 0;
var strlen = number.length;
if(strlen < 13){ return false; }
for(i=0;i
<strlen;i++){
pos = strlen - i;
digit = parseInt(number.substring(pos - 1, pos));
if(i % 2 == 1){
sub_total = digit * 2;
if(sub_total > 9){
sub_total = 1 + (sub_total - 10);
}
} else {
sub_total = digit;
}
sum += sub_total;
}
if(sum > 0 && sum % 10 == 0){
return true;
}
return false;
}
</script>
</head>
<body>
<form>
<input type="text"
name="cc_number"
onblur="if(mod10_check(this.value)){$('#cc_error').hide(); } else { $('#cc_error').show(); }"
value="" />
<span id="cc_er`enter code here`ror" style="display:none;">The card number is invalid.</span>
</form>
</body>
</html>
Does not validate value entered in the textbox. When the textbox goes out of focus message is not shown.Not willing to use any third party plugin.What is wrong with this code?
Try re-writing your inline code as an event handler.
var ccInp = document.getElementById('cc_no');
ccInp.addEventListener('blur', function() {
if(!mod10_check(ccInp.value)) {
document.getElementById('cc_error').style.display = '';
}
});
function mod10_check(val){
var nondigits = new RegExp(/[^0-9]+/g);
var number = val.replace(nondigits,'');
var pos, digit, i, sub_total, sum = 0;
var strlen = number.length;
if(strlen < 13){ return false; }
for(i=0;i
<strlen;i++){
pos = strlen - i;
digit = parseInt(number.substring(pos - 1, pos));
if(i % 2 == 1){
sub_total = digit * 2;
if(sub_total > 9){
sub_total = 1 + (sub_total - 10);
}
} else {
sub_total = digit;
}
sum += sub_total;
}
if(sum > 0 && sum % 10 == 0){
return true;
}
return false;
}
<form>
<input type="text"
name="cc_number"
value=""
id="cc_no"/>
<span id="cc_error" style="display:none;">The card number is invalid.</span>
</form>
jsFiddle: http://jsfiddle.net/8kyhtny2/