Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
My Javascript is off. I am a beginner.
I enter three numbers into three form fields. The addition works, but not the multiply. Also would love an average function. Here's the code.
<!DOCTYPE html>
<html>
<body>
<pre>
<form>
NUMBER1:
<input type="text" id="firstNumber" maxlength="100" size="20">
<br>
NUMBER2:
<input type="text" id="secondNumber" maxlength="100" size="20">
<br>
NUMBER3:
<input type="text" id="thirdNumber" maxlength="100" size="20">
<br><br>
<input name="Calculate Total" type="button" onclick="calculateText();" value="Add Total">
<input type="text" id="Total" maxlength="100" size="20">
<input name="Multiply Total" type="button" onclick="calculateText();" value="Multiply Total">
<input type="text" id="multiplyresult" maxlength="100" size="20">
</form>
</body>
</html>
function calculateText(){
var number1=document.getElementById('firstNumber');
var number2=document.getElementById('secondNumber');
var number3=document.getElementById('thirdNumber');
var result=document.getElementById('Total');
var multiplyresult=document.getElementById('multipyTotal');
var multiplyresult= number1 * number2 * number3;
if(number1.value=="" || number1.value!=parseFloat(number1.value)) number1.value=0;
if(number2.value=="" || number2.value!=parseFloat(number2.value)) number2.value=0;
if(number3.value=="" || number3.value!=parseFloat(number3.value)) number3.value=0;
result.value=0;
result.value=parseInt(result.value);
result.value=parseInt(result.value)+parseInt(number1.value)+parseInt(number2.value)+parseInt(number3.value);
}
And in a jsFiddle: http://jsfiddle.net/kamull61/2shG3/
My comment alluded to some problems with your code; I suspect coming from poor choice of variable names, and you've just confused yourself (we've all been there!). Here is an expanded comment to get you on the right track...
Start by creating better names for your variables:
//these are the input elements, not their values!
var number1Element = document.getElementById('firstNumber');
var number2Element = document.getElementById('secondNumber');
var number3Element = document.getElementById('thirdNumber');
Having done this, it should be obvious that you cannot do something like:
var multiplyresult = number1Element * number2Element * number3Element;
Since those variables represent the input elements and not their values.
Another thing to watch out for: you're declaring a variable multiplyresult as the input element for the multiply result, but then re-declaring that variable as the result of your (albeit erroneous) multiplication:
var multiplyresult = document.getElementById('multipyTotal');
var multiplyresult = number1 * number2 * number3;
Try to make variable names that are descriptive of what the variable represents, this is generally a good practice in programming. It becomes easier for you to spot issues with your code, and more importantly, makes the code easier to read and maintain by someone else in the future (including you, in the future!)
These are things you learn with time and practice - so keep at it!
this was harder because of jsfiddle. onclick events couldn't connect with js below. Making it hard to do it that way. There are two more ways to attach events.
However, i got this take a look http://jsfiddle.net/techsin/2shG3/2/
shortcut for text to number is do some math operation with it instead of parsefloat and int. Works in some situations.
var result=getId('Total'),
multiplyresult=getId('multiplyresult'),
n1,n2,n3;
function getValues(){
n1=getId('firstNumber').value,
n2=getId('secondNumber').value,
n3=getId('thirdNumber').value;
}
console.log((n1)*(n2)*(n3));
window.addIt= function(){ getValues(); result.innerText=(+n1)+(+n2)+(+n3);};
window.multiply= function(){ getValues(); multiplyresult.innerText=(n1)*(n2)*(n3); };
function getId(x){ return document.getElementById(x);}
Related
I'm trying to write a simple Tip Calculator for a computer science class I'm in. It's in HTML/JavaScript. The actual Tip Calculating function is written in JavaScript. I've been told to use innerHTML to display the output of the function in HTML. So from my understanding, innerHTML works by writing any value/variable (in this case the output of my function) to an HTML container with whatever id is defined.
At first I thought maybe it was just my code being in the wrong order. But I've tried moving the function definition around and that wasn't any help. I've verified that the input ID is correct when pulling the variables from HTML. I've done a lot of reading on similar problems and I can't seem to find what I'm doing wrong.
So heres where I define my function, and use innerHTML to write the output. The function is defined before the actual user input.
function calculateTip(){
var checkAmount = document.getElementById("amountBox").value;
var percentTip = document.getElementById("tipBox").value;
var tipTotal = checkAmount * (percentTip / 100);
document.getElementById("tipVar").innerHTML = tipTotal;
}
<body>
<P>
Enter the check amount:
$<input type="numeric" id="amountBox" size=10 value="">
<br>
Tip percentage:
%<input type="numeric" id="tipBox" size=4 value="">
</P>
<input type="button" value="Calculate Tip"
onclick="calculateTip();" >
<hr>
<div id="tipVar"></div>
</body>
So, I'm expecting when you enter the check amount and tip percentage and click the "Calculate Tip" button, it will run the function and innerHTML will write the output of the function to the page in the div container. However when I click the button seemingly nothing happens. If anyone has any help/guidance I'd greatly appreciate it.
You have a typo in the code:
use document.getElementById("tipVar").innerHTML = tipTotal;
Your code was not working because tipVar was undefined, It's an ID and should be used as a string.
I have updated the question snippet and it should work now.
You need to put "tipVar" in quotations inside your function.
Otherwise the value of an undefined variable called tipVar is passed in instead, and it finds no element by that id.
You just forgot the quotes on getElementById("tipBox");
<html>
<body>
<p> Enter the check amount:
<input type="numeric" id="amountBox" size=10 value="">
<br>
Tip percentage:
<input type="numeric" id="tipBox" size=4 value="">
</P>
<input type="button" value="Calculate Tip" onclick="calculateTip();">
<hr>
<div id="tipVar"></div>
<script>
function calculateTip(){
var checkAmount = document.getElementById("amountBox").value;
var percentTip = document.getElementById("tipBox").value;
var tipTotal = checkAmount * (percentTip / 100);
document.getElementById("tipVar").innerHTML = tipTotal;
}
</script>
</body>
</html>
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have this element, it is auto generated by mcssl checkout form. It is a custom field. I'm trying to select it using javascript like so:
var form_field_gclid = document.getElementById("#ctl00_ctl00_mainContent_scPageContent_customFieldsControl_customFieldsRepeater_ctl00_customFieldTextBox");;
console.log(form_field_gclid);
<input name="ctl00$ctl00$mainContent$scPageContent$customFieldsControl$customFieldsRepeater$ctl00$customFieldTextBox" type="text" maxlength="200" size="50" id="ctl00_ctl00_mainContent_scPageContent_customFieldsControl_customFieldsRepeater_ctl00_customFieldTextBox" class="text">
But I'm getting null as a result. I've tried also, document.querySelectorAll(...); but the same result. It's working when I tried it from console but I'm wondering why it won't work if it's on page javascript. Any ideas would be appreciated. Thank you.
I tried getting rid of the # sign but same result.
<script type="text/javascript">
(function() {
var form_field_test = document.getElementById("ctl00_ctl00_mainContent_scPageContent_customFieldsControl_customFieldsRepeater_ctl00_customFieldTextBox");;
console.log(form_field_test);
}());
</script>
This is the full script I'm using.
You do not need the # in your call to document.getElementById. Simply remove it.
var form_field_gclid = document.getElementById("ctl00_ctl00_mainContent_scPageContent_customFieldsControl_customFieldsRepeater_ctl00_customFieldTextBox");
If you were using jQuery, however, you would need it:
var myElement = $('#myElementId');
But since you are using vanilla JS, simply pass in the element's id as a string.
You have to put the script below the html of the input you are trying to hook.
If the form is not rendered the script will return null.
In your webpage you run the script before the input form is rendered.
I think you are looking for the input value. Right?
Also i added a button for you to give you an example about how to add more functionality. For example, how to add a background color to your input
var form_field_gclid = document.getElementById("ctl00_ctl00_mainContent_scPageContent_customFieldsControl_customFieldsRepeater_ctl00_customFieldTextBox").value;
console.log(form_field_gclid);
// add color to your input
function addColor(){
form_field_gclid = document.getElementById("ctl00_ctl00_mainContent_scPageContent_customFieldsControl_customFieldsRepeater_ctl00_customFieldTextBox").style.backgroundColor = "green";
}
If you mean to get the value of the input, i think you are looking for this:
<input name="ctl00$ctl00$mainContent$scPageContent$customFieldsControl$customFieldsRepeater$ctl00$customFieldTextBox" type="text" maxlength="200" size="50" id="ctl00_ctl00_mainContent_scPageContent_customFieldsControl_customFieldsRepeater_ctl00_customFieldTextBox" class="text" value="1">
<button onclick="addColor();">change color</button>
You could try this old school vanilla ::
var form_field_gclid = ctl00_ctl00_mainContent_scPageContent_customFieldsControl_customFieldsRepeater_ctl00_customFieldTextBox;
console.log( form_field_gclid );
<input type="text" maxlength="200" size="50" id="ctl00_ctl00_mainContent_scPageContent_customFieldsControl_customFieldsRepeater_ctl00_customFieldTextBox" class="text">
I'm currently working my way through a beginner's JavaScript course on Treehouse and keep getting stuck on functions. In effort to understand better, I tried creating a calculator which converts human years to dog years. Here is my code so far:
HTML:
<div id="calculator">
<form>
<label>What is your current age in human years? <br>
<input type="text" id="humanYears"></label> <br>
<button type="text" id="calculate">Calculate</button>
</form>
</div>
JS:
function calculate() {
var humanYears = document.getElementById("humanYears").value;
var dogYears = (humanYears * 7);
document.write(dogYears);
}
document.getElementById("calculate").onclick = function(){calculate(); };
The page flickers and I keep seeing the form, no result.
I know this code is incorrect but I don't understand why. I also know I can just copy other people's code from Github and have a functioning calculator but that kind of defeats the purpose of learning. I would rather know why my code doesn't work and what I can do to fix it. (I double, triple checked that the HTML and JS files were properly linked, which they are.)
Any JS wizards out there care to chime in?
Edit: When I enter an age into the form, it merely reloads, rather than displaying the age in dog years (which is the desired outcome).
Your code works, although as you've indicated it's not great.
function calculate() {
var humanYears = document.getElementById("humanYears").value;
var dogYears = (humanYears * 7);
document.write(dogYears);
}
document.getElementById("calculate").onclick = function(){calculate(); };
<div id="calculator">
<form>
<label>What is your current age in human years? <br>
<input type="text" id="humanYears"></label> <br>
<button type="text" id="calculate">Calculate</button>
</form>
</div>
Some notes for improvement:
Avoid document.write
Forms should have submit buttons (either <input type="submit" value="Calculate"> or <button type="submit">Calculate</button>
The parentheses around your arithmetic are superfluous: var dogYear = humanYears * 7; is sufficient
Not everything needs an id attribute, although that makes DOM queries easy and quick
You should handle the form's submit event as opposed to the button's click event as you'll want to handle if, say, I submit the form by pressing Enter on my keyboard
You don't need the extra function around calculate, document.getElementById('calculate').onclick = calculate; would suffice
With those notes in mind, here's how I'd improve your calculator:
var form = document.getElementById('calculator');
function calculate() {
var years = form['humanYears'].value,
dogYears = years * 7;
document.getElementById('answer').innerText = dogYears;
}
form.addEventListener('submit', calculate, false);
<form id="calculator">
<p>
<label>
What is your current age in human years?<br>
<input type="text" name="humanYears">
</label>
</p>
<p>
<button type="submit">Calculate</button>
</p>
<p>
Answer: <span id="answer"></span>
</p>
</form>
Things I've changed:
I'm using <p> tags to control whitespace instead of <br> which will further let me customize presentation with CSS if I choose to. You cannot style <br> elements.
I'm modifying a portion of the DOM, not the entire DOM
I've bound my event handler with addEventListener which is way less obtrusive
I'm accessing form elements through the natural structure the DOM provides instead of running a full DOM query for each element
I've reduced some code
Here your working code with as little changes as possible:
<div id="calculator">
<form>
<label>What is your current age in human years? <br>
<input type="text" id="humanYears"></label> <br>
<button type="text" id="calculate">Calculate</button>
</form>
</div>
<script>
function calculate() {
var humanYears = document.getElementById("humanYears").value;
var dogYears = (humanYears * 7);
document.write(dogYears);
}
document.getElementById("calculate").onclick = function(){calculate(); return false; };
</script>
Assuming you put everything in one file the script tags are missing. If not then you still need a script tag to load the JS file.
Your function needed a "return false;". If you omit that, the page will reload after writing your output and won't see the output. That happens because the default behaviour of a button in a form is to reload the page. By returning "false" you suppress that.
The main problem is that document.write doesn't do what you imagine it does:
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.
See the documentation for document.write: https://developer.mozilla.org/en-US/docs/Web/API/Document/write
A better way to this is to have an empty element on the page, which you then change the contents of:
function calculate() {
var humanYears = document.getElementById("humanYears").value;
var dogYears = humanYears * 7;
document.getElementById('output').innerText = dogYears;
}
document.getElementById("calculate").onclick = calculate;
<div id="calculator">
<form>
<label>What is your current age in human years? <br>
<input type="text" id="humanYears">
</label>
<br>
<button type="button" id="calculate">Calculate</button>
<div id="output"></div>
</form>
</div>
I've also made some small improvements to your script:
Changed the indentation of your HTML to be more readable
Changed your button to have type="button" - otherwise your form will submit and the page will reload when you click the button. In this case, you actually don't even need a form element, but it's not hurting anything. Alternatively, you could add return false to your calculate function - this would tell the browser not to submit the form and thus not reload the page
Changed how you're adding the onclick handler - there's no need to wrap the calculate function in another function. In javascript, functions can actually be passed around like a variable. This is why I set the value of onclick to just be calculate - notice however that I left out the (). You want the onclick to be a reference to the function, otherwise the calculate function would be executed immediately, and the onclick would be set to the return value of the function - in this case, that would be undefined.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Hi I am trying to write a simple calculation that will average the two numbers entered by user input and then click the average button to get the average of the two. MY problem is that it does not produce an answer. Here is the code
<html>
<body>
<input type="text" id="one">
<input type="text" id="two">
<input type ="button" onclick="average()"value="average">
<input type="text" id ="avg">
<script type"text/javascript">>
function average(){
var a=parseInt(document.getElementById("one".value);
var b=parseInt(document.getElementById("two".value);
var afinal=((a+b)/2);
document.getElementById('avg').value=afinal;
}
</script>
</body>
</html>
Typo fix (missing bracket for getElementById):
var a=parseInt(document.getElementById("one").value);
var b=parseInt(document.getElementById("two").value);
and another typo:
<script type"text/javascript">>
should be:
<script type"text/javascript">
so, the final code is:
<html>
<body>
<input type="text" id="one">
<input type="text" id="two">
<input type ="button" onclick="average()"value="average">
<input type="text" id ="avg">
<script type"text/javascript">
function average(){
var a=parseInt(document.getElementById("one").value);
var b=parseInt(document.getElementById("two").value);
var afinal=((a+b)/2);
document.getElementById('avg').value=afinal;
}
</script>
</body>
</html>
Instead of writing the old-school document.getElementById(), consider using an industry-standard, broadly adopted jQuery library, specifically its method called $.
There, you'll be able to use a CSS selector to get to an element that you want. It's extremely powerful, I recommend learning it.
var a = $("#one").val();
It is just a typo fix,
instead of
var a=parseInt(document.getElementById("one".value);
var b=parseInt(document.getElementById("two".value);
the code becomes,
var a=parseInt(document.getElementById("one").value);
var b=parseInt(document.getElementById("two").value);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have a input field like this
<input type="number" id="return_pro" name="available" placeholder="10 Available">
Here if user enter a value more than 10 (That is available), it should not accept and should show an error. How can I do that? I need to use this with the input tag itself. Because text fields comes inside an foreach loop. So number of text fields may increase.
HTML:
<input type="number" id="return_pro" name="available" placeholder="10 Available" onblur="check(this)">
Javascript:
<script>
function check(obj){
var val=obj.placeholder.split(" ")[0];
if(obj.value > parseInt(val)){
alert('invalid');
obj.value="";
obj.focus();
}
}
</script>
The placeholder is just what it says it is, a place holder and has no validation associated.
what you are looking for is some kind of validation, either by javascript/jquery or server side with PHP.
I suggest using a tutorial to learn how validation works like this one here as learning will be infinitely more valuable for the future, than simply copy and pasting some code that people provide on stack overflow.
<input type="number" id="return_pro" name="available" placeholder="10 Available">
<input type="button" value="ok" id="submit"/>
$(function(){
var placeholder=$("#return_pro").attr("placeholder");
var available=parseInt(placeholder.replace(" available",""));
$('#submit').click(function(){
var val=$("#return_pro").val();
if(val>available)
alert("Sorry");
});
});
I think This is actually you looking for.
DEMO HERE
with jQuery
$("#return_pro").keypress(function(){
var intValue = parseInt($(this).val());
if(intValue > 10) {
//value more more then 10, do something
}
});
$('#return_pro').keyup(function(){
var max = $(this).attr('placeholder').match(/[0-9]+/);
if(parseInt($(this).val())>parseInt(max)){
alert('Only '+max+' available');
}
});
DEMO: http://jsfiddle.net/uQH64/