So, I was making a program in html that would convert any decimal number to a binary number, which was working perfectly, then I tried to modify it, and screwed it up somehow. The problem seems to be it takes the value at the start of the runtime, rather than always grabbing it at the moment, but it wasn't doing that before. And, I have no idea why it's doing it, and I'm not completely sure what I'd even look up to look for this kind of error, especially when I have no idea what is wrong.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type = "number" id = 'decimal'></input><br/>
<a id = 'binary'></a>
<script>
setInterval(convert(),1);
function convert() {
var nNum = "";
var num = document.getElementById('decimal').value;
while(num != 0) {
nNum = (num % 2) + nNum;
num = Math.floor(num/2);
}
document.getElementById('binary').innerHTML = nNum;
}
</script>
</body>
</html>
any and all help is greatly appreciated. c:
Try:
<script>
setInterval(convert,1);
function convert() {
var nNum = "";
var num = document.getElementById('decimal').value;
while(num != 0) {
nNum = (num % 2) + nNum;
num = Math.floor(num/2);
}
document.getElementById('binary').innerHTML = nNum;
}
</script>
When you pass function as parameter of function you don't call it convert(), you only pass it convert
Related
Here is the code as far as I got it right now:
<!DOCTYPE html>
<html>
<body>
<button onclick="scanarray('a', 'max')">Test with a, max</button>
<button onclick="scanarray('b', 'min')">Test with b, min</button>
<p id="demo">test</p>
<script>
var array = [{"a":1},{"b":3},{"a":6},{"b":10}];
var max = null;
var min = null;
var value = null;
function scanarray(scanval, searchterm) {
if (array.length < 1) {
return -1;
}
if(searchterm == "max"){
max = Math.max.apply(Math,array.map(function(e){return e.scanvalue;}))
}else if (searchterm == "min"){
min = Math.min.apply(Math,array.map(function(e){return e.scanval;}))
}else
{document.getElementById("demo").innerHTML = "Only max and min available";}
if(searchterm == "max"){
document.getElementById("demo").innerHTML = "Search: " + scanval +" "+ "Value: " + max;
}
if(searchterm == "min"){
document.getElementById("demo").innerHTML = "Search: " + scanval +" "+ "Value: " + min;
}
}
</script>
</body>
</html>
The above should give me a and 6 or b and 3 as results. However I get NaN as result for the value part. When using "return e.a" in the Math section and only having a as keys it works.
I want to be able to determin the max or min value of a key I enter as parameter to the function.
Hope you can help me here.
Thanks in advance.
TheVagabond
There are some naming mess in your code. For example scanvalue is name of your function but you are trying to reach it as a parameter of e(e.scanvalue). I should be scanval. But still there are some problems. You can't reach property "a" or "b" of e if e.scanval. You're trying to reach variable of variable.
Then, you should use e[scanval]. It returns you to value of "a" or "b". But if object doesn't have one of them? Then you should add "|| 0" to get correct value. (Instead of NaN or undefined) It means that; use e[scanval] if its valid, if not use 0.
Use this;
return e[scanval] || 0;
If your boundaries include some negative values, use something like -9999 or -Infinity.
You are getting Nan because e.scanvalue returns undefined in your case.
Try using custom function.
function getValue(arr){
var res = [];
for(var j = 0; j < arr.length; j++)
{
for(var anItem in arr[j])
{
res.push(arr[j][anItem]);
}
}
return res;
}
and call this function like
max = Math.max.apply(Math,getValue(array))
and
min = Math.min.apply(Math,getValue(array))
accordingly.
Hope this helps!!!!
So I am trying to create a function that takes the first input as a number and the second input as a string. the function should then change the innerHTML of the div with the characters of the second input. For example. if the first input was number 2 and second input was hello the innerHTML should change to:
h
ee
if the first was number 5 all else being the same:
h
ee
lll
llll
ooooo
I know I must use str.charAT and possibly a for loop (probably any loop) but just cant seem to piece it together in my head. I have been stuck on this for 6 hours now and I have no idea how to do it. So here I am asking for help XD, help my please! If any hints are out there I would gladly take them, this is just a random exercise to help me get used to js. If you would rather like to give the entire that is fine too, I mean it helps alot more than a hint considering i can learn from it.
the number cannot go past the amount of characters within the string. So far here is the html and javascript that I made.
<html>
<head>
<script src="q2.js" type="text/javascript"></script>
</head>
<body>
<div> Input1<input id="input1" type="text"></div>
<div> Input2<input id="input2" type="text"></div>
<div> Result<div id="result"></div></div>
<button onclick="compute()">Compute</button>
</body>
<html>
JAVASCRIPT:
function compute(){
var n = Number(document.getElementById("input1").value);
var v = document.getElementById("input2").value;
var answer = document.getElementById("result");
var i,j;
answer.innerHTML = "";
if(n){
}else{
alert("whatever is in input 1 is not a number ya fookin cheeky buggah");
}
if(n>v.length){
alert("number 1 bigger than word 2");
}
for(i=0;i<n;i++){
for(j=0;)
}
}
This does what you need, however it may be using some array functions you're not familiar with
function compute() {
var n = Number(document.getElementById("input1").value);
var v = document.getElementById("input2").value;
var answer = document.getElementById("result");
if (!n) {
alert("whatever is in input 1 is not a number ya fookin cheeky buggah");
}
if (n > v.length) {
alert("number 1 bigger than word 2");
}
answer.innerHTML = [].slice.call(v, 0, n).map(function(letter, index) {
return new Array(index+2).join(letter);
}).join('<br />');
}
slice - we only want the first n characters
map - for each character, run the callback function
the callback function creates an Empty array which is 2 larger than the current index (0 based index)
joins this array on the letter - which produces index + 1 letters
the mapped array is joined by <br />
the result of this is output to answer.innerHTML
the answer.innerHTML code in ES2015 (ES6) would be
answer.innerHTML = [].slice.call(v, 0, n).map((letter, index) => letter.repeat(index+1)).join('<br />')
The answer using nested for loops and charAt
function compute() {
var n = Number(document.getElementById("input1").value);
var v = document.getElementById("input2").value;
var answer = document.getElementById("result");
var i, j, c, s = "";
if (n) {
}
else {
alert("whatever is in input 1 is not a number ya fookin cheeky buggah");
}
if (n > v.length) {
alert("number 1 bigger than word 2");
}
for (i = 0; i < n; i++) {
c = v.charAt(i);
if (i > 0) {
s += "<br />";
}
for (j = 0; j <= i; j++) {
s += c;
}
}
answer.innerHTML = s;
}
function compute() {
var n = Number(document.getElementById("input1").value);
var v = document.getElementById("input2").value;
var answer = document.getElementById("result");
if (!n) {
alert("whatever is in input 1 is not a number ya fookin cheeky buggah");
}
if (n > v.length) {
alert("number 1 bigger than word 2");
}
var res ="";
for(var i=1; i<=v.length; i++){
res = res +"\n"+ Array(i+1).join(v.charAt(i));
}
answer.innerHTML = res;
}
Whoever finds this answer to be useful or valid or wrong, please post ur comments or click the up/down arrow. Just to improve myself further.
I am attempting to set up a very basic webpage which essentially documents various coding challenges I have completed.
I am currently attempting to take a value out of JavaScript and place it into an input box in HTML. I understand the usage of innerHTML and getElementById (and I have used both of them before to input a value into a text box) but it seems that I am missing something this time around. I can't seem to get the new value of "sum" to show in the text box.
What am I doing that is incorrect? Is the value of "sum" getting lost in the for / if statement? I apologize if this is overly simple. I cannot find anything that makes this work.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
var sum = 0;
for (i = 0; i < 1000; i++) {
if (i % 3 === 0 || i % 5 === 0) {
sum = sum += i;
}
}
var totalSum = sum;
getElementById("answer1").innerHTML = totalSum;
</script>
<h1>Challenge 1</h2>
<p>Find the sum of all the multiples of 3 or 5 below 1000 (begin with 10, then work up).</p>
<p>Answer is
<input type="text" id="answer1"></input>
</p>
</body>
</html>
input is a single tag element, it cannot have inner HTML. Set the value property instead. Also it's document.getElementById, not just getElementById.
document.getElementById("answer1").value = totalSum;
You should also either put the script below the element or attach it to the window.onload.
<script>
window.addEventListener('load', function () {
var sum = 0;
for (i = 0; i < 1000; i++) {
if (i % 3 === 0 || i % 5 === 0) {
sum = sum += i;
}
}
var totalSum = sum;
document.getElementById("answer1").value = totalSum;
});
</script>
<!DOCTYPE HTML>
<html>
<head>
<title> Untitled </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style type="text/css">
textarea {
overflow: auto;
}
</style>
</head>
<body>
<h1>Challenge 1</h2>
<p>Find the sum of all the multiples of 3 or 5 below 1000 (begin with 10, then work up).</p>
<p>Answer is
<input type="text" id="answer1"></input>
</p>
<script type="text/javascript">
$(document).ready(function(){
var sum = 0;
for (i = 0; i < 1000; i++) {
if (i % 3 === 0 || i % 5 === 0) {
sum = sum += i;
}
}
console.log(sum);
var totalSum = sum;
console.log(totalSum);
document.getElementById("answer1").value = sum;
});
</script>
</body>
</html>
You need to call the getElementById on the document object. Additionally, you are wanting to set the input property, not the innerHTML.
document.getElementById("answer1").value = totalSum;
See example
I could swear it's document.getElementById not just getElementById
Also, try putting your JavaScript at the bottom. You're trying to manipulate an element on the page that hasn't yet been rendered.
var sum = 0;
for (i = 0; i < 1000; i++) {
if (i % 3 === 0 || i % 5 === 0) {
sum = sum += i;
}
}
var totalSum = sum;
document.getElementById("answer1").value = totalSum;
The reason is because you are using the innerHTML property instead of the value property. Input does not have the innerHTML property unlike other DOM elements because it's a single tag element. Also, you have a syntax error : it's document.getElementById not just getElementById.
Here's a working fiddle
im currently doing an assignment where we have a certain amount of people play a game and each player have an attempt of scoring. The scores will be randomly generated from 1-3. The only problem i have is to store the randomly generated value into the array and then summing them up. This way, i can produce a leader board that say something like "congrats (player name) your total score is (total score)). Any suggestion on how to do these's would be great or better yet, any other alternatives would be appreciated as well. So far i've been using a incremental counter to generate the total score but it keeps generating the same number over and over again e.g. (2,2,2,2...) (1,1,1,1,....)
<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function main()
{
randomnumber()
totalscore()
}
function randomnumber()
{
var randomnumber;
randomnumber = Math.random()*3;
return(Math.floor(randomnumber+0.5));
}
function totalscore()
{
var n;
var score = 0;
number = randomnumber();
for (n = 0 ; n < 11 ; ++n)
{
if (number == 0)
{
score = score + 0;
}
else if (number == 2)
{
score =score + 2;
}
else if (number == 3)
{
score =score + 3;
}
}
document.write(score)
}
</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<SCRIPT LANGUAGE = "Javascript"> main() </SCRIPT>
<INPUT NAME = "dobutton" TYPE = "button" value = "Start game" on Click = "game()">
<INPUT NAME = "dobutton" TYPE = "button" value = "Leaderboard" on Click = "leader()">
</BODY>
</HTML>
This may help, although you should try first before posting for solutions.
Create an empty array:
var myArray = [];
Add values to array (from your randomnumber() generator):
myArray.push(randomnumber());
myArray.push(randomnumber());
myArray.push(randomnumber());
Function to sum the values of some array (this is perhaps the most primitive but faster/efficient way to do it):
var sumElements = function(someArray) {
if (someArray == null) return false;
var sum = 0;
for (var i = 0, len = someArray.length; i < len; i++) {
sum += someArray[i];
}
return sum;
}
Call sumElements to find the sum:
sumElements(myArray);
Here is the simplest way to do what you need
var randomArray = [];
var randomSum = 0;
randomArray.push(randomnumber());
randomArray.push(randomnumber());
randomArray.push(randomnumber());
for(var i=0; i<randomArray.lenth; i++){
randomSum += randomArray[i];
}
I am very new to javascript, and have limited knowledge. I have just grasped the concept of hello world. At the moment, my code adds FirstNumber and SecondNumber together to give the result. I would like it to do the following:
I am trying to make a program where FirstNumber is pre-defined as 1 and SecondNumber is done by user input. The javascript should count a sum from 1 to the number that should be entered. For example, if the user entered 5, the program should count the sum from 1 to 5 (1 + 2 + 3 + 4 + 5) which will be 15. I was told to maybe use an array, although I'm not sure.
Here is my HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Sum of numbers</title>
<script type="text/javascript">
function sum()
{
var FirstNumber = 1;
var SecondNumber = document.getElementById('txtSecondNumber').value;
alert(parseInt(FirstNumber) + parseInt(SecondNumber));
}
</script>
</head>
<body>
Please enter a number:<input id="txtSecondNumber" type="text" />
<input id="btnAdd" type="button" value="Add" onclick="sum();"/>
</body>
</html>
Could someone help?
Thanks :)
What you're looking for is a for loop
for (var i = FirstNumber ;i < SecondNumber ; i++){
// do what ever you want in here
// like adding i to the total
}
For the simple case of adding sequential number you dont need to loop at all:
1+2+3+4+5+...+n = n(n+1)/2
Formula from: http://en.wikipedia.org/wiki/1_%2B_2_%2B_3_%2B_4_%2B_%E2%8B%AF
function sum() {
var num = document.getElementById('txtSecondNumber').value;
var sum = (num*(num+1))/2;
alert(sum);
}
While an array might help you with what you want, the important bit you're looking for is a for loop. You don't indicate your programming background or if JavaScript is your first language, but a for loop is a basic programming construct that has a starting condition, an ending condition, a way to change things (so something changes between start and end), and something to do while you're counting.
A simple for loop in JavaScript looks like this:
for( var i=0; i<10; i++ ){
alert( i );
}
This will pop-up an alert for each number from 0 to 9 inclusive.
In your case, you want to set your start condition to the first number, the end condition to check if you've done the last number (both of these can be variables - not just the constants as I've illustrated), and increment the number. Inside the loop, you'll want to be adding the number to a reference counter.
Try this, you want to loop through all the numbers in between the first and second number and add them to the result
var submit = document.getElementById('submit');
var input = document.getElementById('txtSecondNumber');
function sum() {
var FirstNumber = 1;
var SecondNumber = input.value;
var result = 0;
for (var i = FirstNumber; i <= SecondNumber; i++) {
result += i;
}
alert(result);
}
submit.addEventListener('click', sum);
jsFiddle - http://jsfiddle.net/et8t3bgd/
You can easily count a sum from 1 to any number with a for loop. If you will ever only sum up from 1, you do not need the FirstNumber variable. Otherwise, you can change i = 1 to i = FirstNumber.
var sum;
for (i = 1; i < SecondNumber+1; i++) {
sum += i;
}
function sum()
{
var SecondNumber = parseInt(document.getElementById('txtSecondNumber').value);
var result=(SecondNumber *(SecondNumber +1))/2;
alert(result);
}
Formula for sum to 1 to n number is n*(n+1)/2
As per Your Code
<!DOCTYPE html>
<html>
<head>
<title>Sum of numbers</title>
<script type="text/javascript">
function sum()
{
var SecondNumber = parseInt(document.getElementById('txtSecondNumber').value);
var result=(secondnumber*(secondnumber+1))/2;
alert(result);
}
</script>
</head>
<body>
Please enter a number:<input id="txtSecondNumber" type="text" />
<input id="btnAdd" type="button" value="Add" onclick="sum();"/>
</body>
</html>
DEMO
Here
function sum(n) {
var res = 0, total = 0;
while ((n--)>0) total += ++res;
return total;
}
Use a recursive program...
var num=Number(prompt("Enter a number"));
var sum=0;
for(var i=num;i!=0;i--){
sum+=i;
}
console.log(sum)
//print sum