I request some help with updating the result element content with the product of integer input in the text field with a pre-defined variable.
What i wanted to achieve is the content of the element with id="result" to be updated automatically, i want to achieve this using jquery:
Below is my code, thanks in advance.
<script>
function updateresult(){
var operand1 = parseFloat($('slide').val()) || 1;
var operand2 = 25;
var produt;
produt = operand1 * operand2;
$('#result').html(product);
}
</script>
<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div id="text">
Write to change:<input id="slide" type="text" onchange="updateText()" />
</div>
<div >Total is: <span id="result"></span></div>
<br/>
</body>
</html>
You can use keyup event of textbox in jquery.
$("#slide").keyup(function(e){
var operand1 = parseFloat($(this).val()) || 1;
var operand2 = 25;
var result = operand1 * operand2;
$("#result").html(result);
});
Working Sample
There are a couple of things:
your function is named updateresult() but you call a different function: onchange="updateText()"
Instead of $('slide') you need to use an id-selector $('#slide')
you have a typo in product, you sometimes refer to it as poduct
The code below fixes all of that
function updateText(){
var operand1 = parseFloat($('#slide').val()) || 1;
var operand2 = 25;
var product;
product = operand1 * operand2;
$('#result').text(product);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text">
Write to change:<input id="slide" type="text" onchange="updateText()">
</div>
<div >Total is: <span id="result"></span></div>
There is one more thing: The change event gets fired only when the element loses focus, you may want to add paste and keyup events by removing the onchange attribute and add the following to your javascript
$('#slide').on('change keyup paste',updateText);
And yet another thing: you're using <!DOCTYPE HTML> so this is html5. But there are no self-closing tags in html5, so instead of <tag /> you should just write <tag>
Related
I'm trying to get it to add the two numbers inputted by the user, and print it inside of the p tag. Any help would be much appreciated. Here's the code:
<html>
<!DOCTYPE HTML>
<meta charset="UTF-8" name="viewport" content="width=device-width">
<head>
<title>Calculator</title>
</head>
<body>
<h2>Enter in the values you want to add</h2>
<form>
<input id="num1" name="num1" type="number"> //value one
</br>
<input id="num2" name="num2" type="number"> //value two
<button id="calculate">Calculate</button> //Click to calculate
</form>
<p id="p">The answer will show here</p>
<script>
var p1=document.getElementById("p");
var p=p1.innerHTML;
var calc=document.getElementById("calculate");
calc.addEventListener("click", answer); //When the button is clicked it calls the function answer()
function answer() {
var num1=document.getElementById("num1");
var num2=document.getElementById("num2");
var x=num1.innerHTML;
var y=num2.innerHTML;
p=x+y; //print the sum of the two values, inside of the p tag
}
</script>
</body>
To decode what's going on in your JavaScript, please see my annotations to the code:
var p1=document.getElementById("p"); // Stores a reference to an element with id "p" to variable p1
var p=p1.innerHTML; // Retrieves the HTML contents of said attribute and assigns it to variable p (not needed)
var calc=document.getElementById("calculate"); // Stores a reference to an element with id "calc" (your button) to variable calc
calc.addEventListener("click", answer); // Attaches an event handler to the element referenced via variable calc
function answer()
{
var num1=document.getElementById("num1"); // Stores a reference to an element with id "num1" in variable num1
var num2=document.getElementById("num2"); // Stores a reference to an element with id "num2" in variable num2
var x=num1.innerHTML; // Retrieves the HTML contents of the element referenced by num1 and stores it in variable x (error)
var y=num2.innerHTML; // Retrieves the HTML contents of the element referenced by num2 and stores it in variable y (error)
p=x+y; // Since both x and y are strings, they are concatenated and the result is stored in variable p (produces wrong result)
// Missing assignment of result to output element
}
The problem: You don't have a statement that actually assigns the result to the paragraph marked with ID "p", instead you are modifying a variable.
Furthermore, since you are retrieving strings from the input fields, the addition is in reality a concatenation, producing a false result (num1.value and num2.value are needed to access the actual values). I'd also suggest converting things to an integer - parseInt does the trick here.
There are several errors in your code, will try to address them one by one:
The <button> by default is type="submit" which when pressed refreshes the whole page, not the intended behaviour. To fix it just need to add type="button", which makes it behabe like a button that by itself does nothing.
The result of p=x+y, you are doing nothing with it. p is just a variable containing the result of the operation, but you need then to insert it inside the <p> tag for it to show up. Adding this at the end of your answer() function should fix it: p1.innerHTML = p;.
The <input> values, those are stored in the value property instead of the innerHTML. So it should look like this var x=num1.value; and var y=num2.value;.
The "sum", in JavaScript the + operator can be used both to add numerical values and to concatenate strings, and the engine chooses what to do guessing by the type of the values you are using, in your case strings. Because even if you type 1 in the input, retrieving it later with .values will return it as a string. You have to cast it back to a number to get the desired result. Just doing this is enought var x=Number(num1.value); and var y=Number(num2.value);.
And that's all.
Here you have your code with the fixes applied.
<html>
<!DOCTYPE HTML>
<meta charset="UTF-8" name="viewport" content="width=device-width">
<head>
<title>Calculator</title>
</head>
<body>
<h2>Enter in the values you want to add</h2>
<form>
<input id="num1" name="num1" type="number"> //value one
</br>
<input id="num2" name="num2" type="number"> //value two
<button type="button" id="calculate">Calculate</button> //Click to calculate
</form>
<p id="p">The answer will show here</p>
<script>
var p1=document.getElementById("p");
var p=p1.innerHTML;
var calc=document.getElementById("calculate");
calc.addEventListener("click", answer); //When the button is clicked it calls the function answer()
function answer() {
var num1=document.getElementById("num1");
var num2=document.getElementById("num2");
var x=Number(num1.value);
var y=Number(num2.value);
p=x+y; //print the sum of the two values, inside of the p tag
p1.innerHTML = p;
}
</script>
</body>
Sorry for the lengthy answer but tried to attack each error by itself and it's explanation as clear and simple as I can do.
p = p1.innerHTML
copies the contents of your paragraph into the variable p.
So your
p = x+y
merely assigns a new value to your variable p and doesn't change the innerHTML of your paragraph.
Try
p1.innerHTML = (x + y) + ''; // + '' converts the result of x + y to a string
You should also use '.value' instead of '.innerHTML' to get the contents of your inputs and then convert them to numbers with parseInt() before adding them.
There were quite a few issues; you can't copy the innerHTML of a p and then assign it a value. You must convert the input values to integers in order to add them. With inputs you can ask for their "value" rather than innerHTML.
<html>
<!DOCTYPE HTML>
<meta charset="UTF-8" name="viewport" content="width=device-width">
<head>
<title>Calculator</title>
</head>
<body>
<h2>Enter in the values you want to add</h2>
<form>
<input id="num1" name="num1" type="number"> //value one
</br>
<input id="num2" name="num2" type="number"> //value two
<button id="calculate">Calculate</button> //Click to calculate
</form>
<p id="p">The answer will show here</p>
<script>
var p1=document.getElementById("p");
var calc=document.getElementById("calculate");
calc.addEventListener("click", answer); //When the button is clicked it calls the function answer()
function answer(e) {
e.preventDefault();
var num1=document.getElementById("num1");
var num2=document.getElementById("num2");
var x=parseInt(num1.value, 10);
var y=parseInt(num2.value, 10);
p1.innerHTML = x+y; //print the sum of the two values, inside of the p tag
}
</script>
</body>
</html>
So, I'm trying to build a decimal to binary converter for my computer science class. I already made an algorithm in Python that seems to be working pretty well. It works in the Javascript console perfectly fine too. I'm now at a point trying to accept input from an HTML form. I'm kind of a DOM noob, but I thought this would be something easy and fun to do, but it's turning out that it's a lot more confusing than I thought. I would know how to do this in React.js, but I'm trying to use this as a learning experience. Basically, I want to take input from a form, run it through a function and have the returned value of the function back into HTML. I know how to get the value into HTML, but I have no clue how to retrieve the form data into Javascript. Here's a Codepen with my progress so far.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript Binary Calculator</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<center><form style="margin-top: 25%" id="myForm">
<input type="text" class="form-control" style="width: 250px" placeholder="Type a number!" id="textForm">
<br />
<input type="button" class="btn" style="margin-top: 15px" value="Submit">
</form></center>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script src="script.js" type="text/javascript"></script>
</body>
</html>
Javascript:
function conversion(){
var quotient = 15;
var convertedNum = [];
if (formValue == 0){
convertedNum = [0]
}
while(formValue >= 1){
quotient = formValue/2;
var mod = formValue %2;
formValue = quotient;
convertedNum.push(mod);
convertedNum.reverse();
}
console.log(convertedNum.join(""));
}
$('#textForm').change(function(){
var formValue = document.getElementById('#textForm').value;
parseInt(formValue);
console.log(formValue);
console.log("It's Working in Console!");
conversion();
});
Her's a simple way doing what you are trying to accomplish.
function myFunction() {
var x = document.getElementById("myText").value;
document.getElementById("demo").innerHTML = x;
}
</script>
<body>
First Name: <input type="text" id="myText" >
<p>Click the button to display the value of the value attribute of the text field.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
You want to put the answer back onto the page to be displayed when they click submit?
First you'll need a container (well, you can create one on the fly in Javascript, but typically you would just create an empty div container to hold the answer).
Add a div container for the solution: (after form probably)
<div id="convertedToBinary" class="answerDiv"></div>
It looks like you're using jQuery, which makes entering HTML into a target easy.
Add this to your conversion function:
$('#convertedToBinary').html(formValue+" converted to binary is: "+convertedNum.join("") );
<head>
<title></title>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
</head>
<body>
<input type="text" class="form-control" />
<span id="result"></span>
<script>
var formValue;
function conversion()
{
var quotient = 15;
var convertedNum = [];
if (formValue == 0)
{
convertedNum = [0]
}
while (formValue >= 1)
{
quotient = parseInt(formValue / 2);
var mod = formValue % 2;
formValue = quotient;
convertedNum.push(mod);
convertedNum.reverse();
}
$('#result').html(convertedNum.join(""));
}
$('.form-control').keydown(function ()
{
var $this = $(this);
setTimeout(function ()
{
formValue = $this.val();
conversion();
}, 100);
});
</script>
</body>
</html>
Just a couple of hints starting from the HTML / JS you provided:
You are using a jQuery selector within plain JS, so this won't work:
var formValue = document.getElementById('#textForm').value;
Change that to
var formValue = document.getElementById('textForm').value;
if you want to use plain JavaScript - or do it the jQuery way, like so
var formValue = $('#textForm').value;
You could also have stored the reference to that DOM element in a var, up front, and then work on that, but that's another topic.
Also you must pass the formValue to the conversion function, like so
conversion(formValue);
otherwise you can't work with the input value within the function scope.
All that remains to do is writing the resulting value into the innerHTML of some . The other answers give you two options for doing that - in jQuery (innerHTML) or plain old JavaScript.
hi so i am new to javascript and i am trying to make a simple calculator using HTML and js. However i have run into a problem where i press the button to calculate the answer and it wont do anything. I tried it in an online ide and it just gave me the wrong answer. here is the code can anyone help. thanks--
<!DOCTYPE html>
<html>
<head>
<title>calculator</title>
<script type="text/javascript">
document.getElementById("equals").onclick = function() {
var answer = parseInt(document.getElementById('number_1').value)+ parseInt(document.getElementById('number_1').value);
document.getElementById('answer').innerHTML = answer;
};
</script>
</head>
<body>
<input type="text" name="number_1" id = "number_1">
<p>+</p>
<input type="text" name="number_2" id = "number_2">
<input type="submit" name="equals" id = "equals" value="=">
<p id = "answer"></p>
</body>
</html>
forms including onClick conditions without GET/POST methods , generally use button .
<input type="button" name="equals" id="equals" value="=">
I guess you are adding same variables twice ?
var answer = parseInt(document.getElementById('number_1').value)+ parseInt(document.getElementById('number_2').value);
You're adding the value from the same input twice and you have to set the event handler after the button is created, .
<body>
<input type="text" name="number_1" id = "number_1">
<p>+</p>
<input type="text" name="number_2" id = "number_2">
<input type="submit" name="equals" id = "equals" value="=">
<p id = "answer"></p>
<script type="text/javascript">
document.getElementById("equals").onclick = function() {
var answer = parseInt(document.getElementById('number_1').value)+ parseInt(document.getElementById('number_1').value);
document.getElementById('answer').innerHTML = answer;
};
</script>
</body>
The main problem is you are adding the event click to element equals, but in these moment, element equals doesn't exists.
wrap your document.getElementById into window.onload function to say javascript: "when all the document finish to load, add the event click to element equals"
try this:
window.onload = function () {
document.getElementById("equals").onclick = function() {
var answer = parseInt(document.getElementById('number_1').value, 10)+ parseInt(document.getElementById('number_2').value, 10);
document.getElementById('answer').innerHTML = answer;
};
}
Another important thing I have added ,10 to your parseint, this is to make sure that the conversion is to a number into decimal mode
"The parseInt() function parses a string and returns an integer.
The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.
If the radix parameter is omitted, JavaScript assumes the following:
If the string begins with "0x", the radix is 16 (hexadecimal)
If the string begins with "0", the radix is 8 (octal). This feature is deprecated
If the string begins with any other value, the radix is 10 (decimal)"
Source: parseInt use
i fixed it now i had to wrap my code in a window.onload
<!DOCTYPE html>
<html>
<head>
<title>calculator</title>
<script type="text/javascript">
window.onload = function(){
document.getElementById("equals").onclick = function() {
var answer = parseInt(document.getElementById('number_1').value)+ parseInt(document.getElementById('number_2').value);
document.getElementById('answer').innerHTML = answer;
};
};
</script>
</head>
<body>
<input type="text" name="number_1" id = "number_1">
<p>+</p>
<input type="text" name="number_2" id = "number_2">
<button id = "equals">=</button>
<p id = "answer"></p>
</body>
</html>
Hello SO I'm relatively new to html and javascript and I currently want to make a page that will fulfill certain operations such as finding the max number of an array of numbers and factorial of a number as shown below.
and here is how I am organizing these sections
<!DOCTYPE html>
<html lang = "en">
<head>
<title>HTML/CSS Responsive Theme</title>
<meta charset = "utf-8">
<link rel = "stylesheet" href = "main.css" type = "text/css">
<meta name = "viewport" content = "width=device-width, initial-scale=1.0">
<script>
function startFactorial(number)
{
function factorial(num)
{
if(num <= 1)
return 1;
return num * factorial(num - 1);
}
document.factorials.factorialsfield.value = factorial(number);
}
function startMaxofFive(str)
{
//can actually find the max of n numbers not limited to 5
function maxoffive(string)
{
var nums = (string.match(/[-]?\d+/g));
var b = nums.map(Number);
return Math.max.apply(Math,b);
}
document.mof.moffield.value = (maxoffive(str));
}
</script>
</head>
<body>
<section id = "first">
<h3>Factorial</h3>
<form name= "factorials">
Enter a number <input type = "number" name = "factorialsfield" value = 0>
<br><br>
<input type = "button" onClick = "startFactorial(factorialsfield.value)" value = "Calculate"/>
</form>
</section>
<br>
<section id = "second">
<h3>Max of Five Numbers</h3>
<form name = "mof">
Enter 5 numbers <input type = "text" name = "moffield" placeholder = " separate each number by commas" size = 26>
<br><br>
<input type = "button" onClick = startMaxofFive(moffield.value) value = "Calculate"/>
</form>
</section>
<br>
<section id = "third">
<h3>Sum and Multiply</h3>
<form name = "operations">
Enter numbers to apply operations <input type = "text" name = "operationsfield"
</form>
</section>
</body>
</html>
What I wanted to ask you all is is there a better way to access those functions in my script without having to create another function just to use them?
Here's some suggestions:
You can use document.getElementById( id ) to get specific elements where id is the HTML's element id <element id="id_name">.
Events allow you to trigger actions based on user input. It works basically the same, but you no longer need to name the functions: element_variable.event = function() { /* ... */ }
See if the inner functions are really neccessary; see if you can edit the code where you no longer need that function (document.getElementById will probably be able to let you do that stuff)
Example:
<form id="factorials" name="factorials">
<!-- Skipping input -->
<input type="submit" <!-- ... -> />
</form>
// Javascript file
var fact = document.getElementById( "factorials" );
fact.onsubmit = function() {
/* Your code here */
}
It's generally considered best practice to move scripts to the bottom of the page before the closing body tag. This way the loading of the scripts won't interfere with page load.
You can also move your scripts to a separate file and include it:
<script src="myscripts.js"></script>
This will help keep your code more neat and organized.
You always use functions to call functions. Sounds weird but thats how it is :P
You can remove the JS calls from your DOM by adding eventlisteners to your JavaScript file just like this example:
<script>
var x = document.getElementById('test');
x.addEventListener('click', function(){
// your function magic happens here
});
</script>
<div id="test"></div>
Sorry if I understood your question wrong
I am not sure that this is what you asked for, however, it seemed like you wanted to know about other methods to get access to your javascript code or script in your HTML.
I can truly recommend you, to look into Angular for this. With Angular you can call methods in your controller, and scope data between your view (HTML) and controller (Javascript).
https://angularjs.org/
But this is just one of many options!
Now this is just for reference for a future project but I am trying to call a function that reads in a string but displays a float after. So I first check the string then display a random number. The problem I am having, I think, is with the document.getElementById part. Any suggestions??
HTML File:
<html>
<body>
<input type="text" id="letter" value=""/><br/>
<input type="button" value="LETS DO THIS!" onclick="floatNum();"/></br>
<script type="text/javascript" src="letNum.js"></script>
</body>
</html>
External JS File:
function floatNum()
{
var val1 = document.getElementById("letter");
if (isNaN(val1)
{
alert(Math.random())
}
}
the following code is working:-
in your code,you missed closing parenthesis ")" near to "if condition"
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>demo</title>
<script type="text/javascript">
function floatNum()
{
var letter = document.getElementById("letter");
if (isNaN(letter.value))// using input fields value not the whole object
{
alert(Math.random());
}
}
</script>
</head>
<body>
<input type="text" id="letter" value="" /><br />
<input type="button" value="LETS DO THIS!" onclick="floatNum();" />
</body>
</html>
Yes, you want to pass in the element in the function, like so:
<input type="button" value="LETS DO THIS!" onclick="floatNum(document.getElementById('letter'))"/></br>
And in your JS
function floatNum(el)
{
if (isNaN(el)
{
alert(Math.random())
}
}
In case of a reusable function - try not to make it dependent on your DOM. Think about what would happen if you rename your element or want to use this function again. You couldn't before - now you can.
The problem is on this line:
var val1 = document.getElementById("letter");
It should be:
var val1 = document.getElementById("letter").value;
The first sets val1 to the DOM element representing the input tag, the second sets it to the text value of the input tag (its contents).
You need to process the value of input field not the input field itself.
function floatNum()
{
var letter = document.getElementById("letter");
if (isNaN(letter.value) // using input fields value not the whole object
{
alert(Math.random())
}
}
You don't grab the value of the input, but the input itself.
Correct code would be :
var val1 = document.getElementById("letter").value;