I want to make a program which can sum up all the digits in a given number. I want my script to return the resul on click of the button Please help me find error in my code. Thanks
<!doctype html>
<html>
<head>
<script type="text/javascript">
function sumdigits()
{
var num=document.getElementById("a").value;
var len=num.length();
alert(len);
if(len!=0)
{
var sum=0;
var ldigit=0;
while(num!=0)
{
ldigit=num%10;
sum+=ldigit;
num/=10;
}
}
document.getElementById("result").innerHTML="Sum of digits of the given number="+sum;
}
</script>
</head>
<body>
Enter a number: <input type="text" id="a" name="t1"><br/>
<input type="button" name="sub" value="Submit" onClick="sumdigits()">
<div id="result"> </div>
</body>
</html>
DEMO
onClick should be onclick, length() should be length and sum not out of scope
function sumdigits(){
var num = document.getElementById("a").value;
var len = num.length; // note "length"
var sum; // "sum" scope
alert(len);
if(len!==0){
sum = 0;
var ldigit=0;
while(num!==0){
ldigit=num%10;
sum += ldigit;
num /= 10;
}
}
document.getElementById("result").innerHTML="Sum of digits of the given number = "+ sum;
}
This is how to make it work, now, I don't know what math you're trying to apply in there and what's it's purpose...
The main reason the script is breaking is because you are calling length() on num variable instead of num.length. Below is a link to a working fiddle with that and a few other adjustments made ( check to see if the value's are integers etc...).
http://jsbin.com/uBAyOJep/1/
<!doctype html>
<html>
<head>
</head>
<body>
<form onsubmit="sumdigits()">
Enter a number: <input type="text" id="a" name="t1"><br/>
<input type="button" name="sub" value="Submit" onClick="sumdigits()">
<div id="result"> </div>
</form>
</body>
</html>
function sumdigits()
{
var sum = 0,
num = document.getElementById("a").value,
len = num.length,
result = document.getElementById("result");
if( len !== 0 ){
for( var i = 0; i < len; i++){
var lineValue = parseInt(num[i], 0);
if ( !isNaN(lineValue) ) {
sum += lineValue;
}
}
}
result.innerHTML="Sum of digits of the given numbers = " + sum;
}
Related
I just wrote this in order to take n from user and also n names , and then print them on screen after clicking on button , but i cant initialize my array ...
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<script>
var n;
var i =0;
var names = [];
function mf1(){
n=parseInt(document.getElementById("n").value);
}
function mf2(){
if (i<n){
names[i]=document.getElementById("nam").value;
i++;
document.getElementById("rem").innerHTML=names[i];
}
}
</script>
inset n : <input type="text" id="n"> <button onClick="mf1()">take n</button>
insert name: <input type="text" id="nam"> <button onClick="mf2()"> take name</button>
<p id="rem"></p>
</body>
</html>
The problem is that in function mf2 you can't access names[i] because you increment i++ before.
var n;
var i = 0;
var names = [];
var input1 = document.getElementById("n");
var input2 = document.getElementById("nam");
function mf1(){
n = parseInt(input1.value);
console.log(n);
}
function mf2(){
if (i < n){
names[i] = input2.value;
console.log(names);
document.getElementById("rem").textContent = names[i];
i++;
}
}
Hey guys im trying to create a function that takes 3 arguments. The first argument is supposed to be "MULTIPLY" or "DIVIDE" in an input field, then followed by two numbers which are also in separate input fields, that should be either multipled or divided according based on the first argument. I cant figure out exactly how i'm supposed to write this down in code.
this is my code so far;
<!DOCTYPE html>
<html>
<head>
<script src="ovning3-3.js"></script>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1></h1>
<p>
</p>
<input id="first" type="text">
<input id="second" type="text">
<input id="third" type="text">
<input type="button" value="Multiply" onclick="multiply()">
<input type="button" value="Divide" onclick="divide()">
<input type="button" value="Multiply and Divide" onclick="multiplyAndDivide()">
</body>
</html>
and the java script;
function multiply() {
var x = document.getElementById("first").value;
var y = document.getElementById("second").value;
var z = document.getElementById("third").value;
var result = (x * y) * z
alert(result)
}
function divide() {
var x = document.getElementById("first").value;
var y = document.getElementById("second").value;
var z = document.getElementById("third").value;
var result = (x / y) / z
alert(result)
}
function multiplyAndDivide() {
multiply();
divide();
}
Any help out there?
You can use only one function
function multiplyOrDivide(todo){
var x = document.getElementById("first").value;
var y = document.getElementById("second").value;
var z = document.getElementById("third").value;
if(todo==0){
alert(Number(x*y*z));
}
else{
if(y!=0 || z!=0){
alert(Number(x/y)/z);
}
}
}
In onclick you can pass options as multiplyOrDivide(1)
See if this is what you want
<!DOCTYPE html>
<html>
<head>
<script>
function calculate() {
var x = document.getElementById("first").value;
var y = document.getElementById("second").value;
var d = document.getElementById("decision").value;
if (d=="*")
result = x*y;
else if(d=="/")
result = x/y;
alert(result)}
</script>
<title></title>
</head>
<body>
<h1></h1>
<select id="decision">
<option value="*">Multiply</option>
<option value="/">Divide</option>
</select><br>
<input id="first" type="text">
<input id="second" type="text"><br>
<input type="button" value="Calculate" onclick="calculate()">
</body>
</html>
Let me know if you need any further explaination
You can use select menu to choice which operation you want to perform. To use js functionality, you can take a look this:
function calculate() {
var selected_operation = document.getElementById("operation");
var operation = selected_operation.options[selected_operation.selectedIndex].value;
if (operation == 'multiply')
multiply(operation);
else if (operation == 'divide')
divide();
else if (operation == 'mulitiply_division')
multiplyAndDivide();
}
function multiply() {
var x = document.getElementById("first").value;
var y = document.getElementById("second").value;
var z = document.getElementById("third").value;
var result = (x * y) * z
alert(result);
}
function divide() {
var x = document.getElementById("first").value;
var y = document.getElementById("second").value;
var z = document.getElementById("third").value;
var result = (x / y) / z
alert(result);
}
function multiplyAndDivide() {
multiply();
divide();
}
To see the whole scenario, please visit DEMO
function mul()
{
var a = document.getElementById("v1").value;
var b = document.getElementById("v2").value;
document.getElementById("ans").innerHTML = "Multiplication is: " + a * b;
}
function div()
{
var a = document.getElementById("v1").value;
var b = document.getElementById("v2").value;
document.getElementById("ans").innerHTML = "Division is: " + a / b;
}
<!DOCTYPE html>
<html>
<head>
</head>
<style>
body{
padding-left: 80px;
}
</style>
<body>
<p id="ans"></p>
<input type="text" placeholder="Value 1" id="v1"><br><br>
<input type="text" placeholder="Value 2" id="v2"><br><br>
<input type="button" onclick="mul()" id="mul" value="Multiplication">
<input type="button" id="div" onclick="div()" value="Division">
</body>
</html>
Explanation:
document.getElementById(id).value: The value property sets or returns the value of the value attribute of a text field.
document.getElementById("result").innerHTM : The innerHTML property sets or returns the HTML content (inner HTML) of an element.
This question already has answers here:
How to find prime numbers between 0 - 100?
(40 answers)
Closed 9 years ago.
I'm just trying to find prime numbers of an entered range of numbers. I have no clue how to calculate finding primes. I need to add them to an array and output the array after. I put a placeholder for the calculation... I just can't seem to figure out how find the primes.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>LeapYears</title>
<script type="text/javascript">
/* <![CDATA[ */
function calcPrimeNumber(){
var beginNum = document.numbers.firstNum.value;
var endNum = document.numbers.secondNum.value;
var primeNumbs = new Array();
var ctr = 0;
while (beginNum <= endNum){ //throwaway
if ((beginNum % beginNum == 0) && (beginNum % 1 == 0)){
primeNumbs[ctr] = beginNum;
++ctr;
}
++beginNum;
}
if (primeNumbs == 0){
window.alert("There were no leap years within the range.");
}
else {
outputPrimeNums(primeNumbs);
}
}
function outputPrimeNums(primes){
document.write("<h2>Prime Numbers</h2>");
for (i=0;i<primes.length;i++){
document.write(primes[i] + "<br/>");
}
}
/* ]]> */
</script>
</head>
<body>
<form name="numbers">
Beginning Number: <input type="text" name="firstNum" /> End Number: <input type="text" name="secondNum" />
<input type="button" value="Find Prime Numbers" onclick="calcPrimeNumber()" />
</form>
</body>
</html>
try this full page of prime no example
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>LeapYears</title>
<script type="text/javascript">
/* <![CDATA[ */
function calcPrimeNumber(){
var beginNum = parseInt(document.numbers.firstNum.value);
var endNum = parseInt(document.numbers.secondNum.value);
var primeNumbs = new Array();
var ctr = beginNum;
while(ctr<=endNum)
{
if(isPrime(ctr)==true)
{
primeNumbs[primeNumbs.length] = ctr;
}
ctr = ctr+1;
}
if (primeNumbs.length == 0){
document.getElementById('output_content').innerHTML = "There were no prime no within the range.";
}
else {
outputPrimeNums(primeNumbs);
}
}
function isPrime(num)
{
var flag = true;
for(var i=2; i<=Math.ceil(num/2); i++)
{
if((num%i)==0)
{
flag = false;
break;
}
}
return flag;
}
function outputPrimeNums(primes){
var html = "<h2>Prime Numbers</h2>";
for (i=0;i<primes.length;i++){
html += primes[i] + "<br/>";
}
document.getElementById('output_content').innerHTML = html;
}
/* ]]> */
</script>
</head>
<body>
<form name="numbers">
Beginning Number: <input type="text" name="firstNum" /> End Number: <input type="text" name="secondNum" />
<input type="button" value="Find Prime Numbers" onclick="calcPrimeNumber()" />
</form>
<div id="output_content">
</div>
</body>
</html>
You should use some algorithm to check whether a given no is prime no or not inside while loop .
http://en.wikipedia.org/wiki/Prime_number
http://en.wikibooks.org/wiki/Efficient_Prime_Number_Generating_Algorithms
You need two loops here - the first to run between beginNum and endNum and the second to run from 1 to beginNum for each value of beginNum in the outer loop.
Try replacing the main section of your code with the following. (For clarity, I'm going to introduce a new variable - numberBeingTested.)
var ctr = 0;
var numberBeingTested = beginNum;
while (numberBeingTested <= endNum){ //throwaway
var testDivisor = 2;
var isPrime = true;
while (testDivisor < numberBeingTested ){ //throwaway
if (numberBeingTested % testDivisor == 0) {
isPrime = false;
}
++testDivisor;
}
if (isPrime){
primeNumbs[ctr] = numberBeingTested;
++ctr;
}
++numberBeingTested;
}
Note that there are many possible improvements here - for a start, this code as it stands will tell you that 1 is prime, and there are significant possible performance improvements (such as testing possible divisors up to the square root of the number being tested rather than the number itself) - but for your purposes it will probably suffice.
What I try was to edit Sieve of Atkin algorithm from linked question:
function getPrimes(min, max) {
var sieve = [], i, j, primes = [];
for (i = 2; i <= max; ++i) {
if (!sieve[i]) {
// i has not been marked -- it is prime
if (i >= min) {
primes.push(i);
}
for (j = i << 1; j <= max; j += i) {
sieve[j] = true;
}
}
}
return primes;
}
console.log(getPrimes(10, 100));
This will give you array with prime numbers from min to max. It still has to go through all number from 2, so maybe there will be more effective way how to achieve this.
I tried using the following code to format a text field value from (N50,000.00 NGN) to (50000) but the result instead of producing 50000 is producing 5000000.
Can someone please help?
<script type="text/javascript" language="javascript">
function doWork() {
var amount = document.getElementsByName('amount');
var str = amount[0].value;
var temp = '';
for (i = 0; i < str.length; i++) {
if (!isNaN(str[i]))
temp += str[i];
}
amount[0].value = temp;
}
</script>
<input type="text" name="amount" value="N50,000.00 NGN" />
<input type="button" value="submit" onclick="doWork();">
The simplest method to get what you want might be to just add another condition in your for loop:
if (str[i] === '.')
break;
Let's take a look at the value you are trying to format.
In N50,000.00 NGN all digits are not NaN. So your result is 5000000 (50 000 00). The solution is to stop at dot symbol, e.g.
function doWork() {
var amount = document.getElementsByName('amount');
var str = amount[0].value;
var temp = '';
for (i = 0; i < str.length; i++) {
if (str[i] === '.') break; // there it is
if (!isNaN(str[i]))
temp += str[i];
}
amount[0].value = temp;
}
Here's one way to do it with a regex. Note, that if the user has multiple decimal points in the input field it may act oddly.
<script type="text/javascript" language="javascript">
function doWork() {
var amount = document.getElementsByName('amount');
amount[0].value = amount[0].value.replace(/[^0-9.]/g, "");
amount[0].value = amount[0].value.replace(/[.][0-9]*/g, "");
}
</script>
<input type="text" name="amount" value="N50,000.00 NGN" />
<input type="button" value="submit" onclick="doWork();">
The first line removes all characters except numbers and decimal points.
The second, removes all decimal points and any numbers to the right of them.
Using parseInt and toFixed may be better, though:
<script type="text/javascript" language="javascript">
function doWork() {
var amount = document.getElementsByName('amount');
amount[0].value = parseInt(amount[0].value.replace(/[^0-9.]/g, "")).toFixed(0);
}
</script>
<input type="text" name="amount" value="N50,000.00 NGN" />
<input type="button" value="submit" onclick="doWork();">
You're skipping over the decimal. Use:
if (!isNaN(str[i]) || str[i]=='.')
I sort of started coding for this. It's almost working.
My goals:
1) Check for the length or url's entered in a field (the total length) and reduce each link's length by 20 if the length is greater than 20
2) Determine the characters left in an input field
The javascript in profile.js (prototype):
function checkurl_total_length(text) {
var text = "";
var matches = [];
var total_length = 0;
var urlRegex = /(http|https):\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;
text.scan(urlRegex, function(match){ matches.push(match[0])});
for (var index = 0; index < matches.length; ++index) {
item = matches[index];
reduce_length = matches.length*20;
if(item.length>20) {
total_length = total_length + item.length - reduce_length;
}
else {
total_length = total_length + item.length;
}
}
return total_length;
}
function count_characters(field){
var limitNum=140;
var link_length = 0;
if(checkurl_total_length(field.value)!=0) {
link_length =link_length+ checkurl_total_length(field.value);
}
else {
link_length = 0;
}
limitNum = limitNum+link_length;
if( link_length !=0 ){
$("links").update("with links");
}
left = limitNum-field.value.length;
$("count").update(left);
}
THE HTML
<!DOCTYPE HTML>
<html lang="en"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>JUST A TEST FILE</title>
<script src="prototype.js" type="text/javascript"></script>
<script src="profile.js" type="text/javascript"></script>
</head><body>
<h1>
CHARACTERS COUNT
</h1>
<div class="container_24">
<h2 id="title2">
TESTING
</h2>
<div class="grid_24">
<div id="count"></div>
<br /s>
<div id="links"></div>
<form >
<textarea wrap="hard" onpaste="count_characters(this);" onkeyup="count_characters(this);" onkeydown="count_characters(this);" id="updates" onfocus="count_characters(this);" name="test"/> </textarea>
<input type="submit" value=" " name="commit" disabled=""/>
</form>
</div>
</div>
<!-- end .container_24 -->
</body></html>
Counting characters left is working but checking for url and the length of the url isn't. Any hints on why this isn't working?
not sure, but should this be
checkurl_total_length(field.value!=0) // ) != 0