Calculating a number using a textbox - javascript

I've been trying to calculate a number using a number given by a user in a text box. I've been trying to use the following code. But when I try to test it, nothing happens. Is there something I'm missing? And is there a way that I can make the imprint variable global?
<form>
<p>How many products do you want
ingraved?<input id="imprint_amount" name="imprint_amount" type="text"/>
</p>
<p>Names to be Imprinted(one per
line)<TEXTAREA COLS=25 NAME="imprint_text" ROWS=5 WRAP=HARD style="resize:none;"></textarea>
</p>
<input onclick="imprint_price" type="button" value="Finish"/>
<p id="total_cost"></p>
</form>
<script type="text/javascript">
function imprint_price() {
var imprint_cost,
imprint_quality,
imprint_total;
imprint_cost = 10.99;
imprint_quantity = document.getElementById('imprint_amount');
imprint_total = $imprint_cost * parseInt(imprint_quantity, 10);
document.getElementById('total_cost') = "$" + imprint_total;
}
Thanks,
Traci

You will want to use the value property of that input element you are referencing in your variable:
… parseInt(imprint_quantity.value, 10);
For arbitrary HTML elements, you need to use textContent (or innerText to support old IE):
document.getElementById('total_cost').textContent = …;
Assigning to an expression as you did should have thrown a quite accurate exception, check your browser's error console for them.

Change your javascript to:
<script type="text/javascript">
function imprint_price() {
var imprint_cost,
imprint_quantity,
imprint_total;
imprint_cost = 10.99;
imprint_quantity = document.getElementById('imprint_amount').value;
imprint_total = imprint_cost * parseInt(imprint_quantity, 10);
document.getElementById('total_cost').innerHTML = imprint_total;
}
</script>
Working jsFiddle here http://jsfiddle.net/Zt38S/2/

In this line, you'll want to set the innerHTML of the element.
document.getElementById('total_cost').innerHTML = "$" + imprint_total;
This basically sets the text inside the <p></p> to be <p>$x.xx</p>.
And also this line should be
imprint_quantity = document.getElementById('imprint_amount').value;
which retrieves the value from the textbox.
Furthermore, when defining the variables, you wrote "quality". It should be
imprint_quantity,

imprint_quantity = document.getElementById('imprint_amount');
=
imprint_quantity = document.getElementById('imprint_amount').value();
Lemme know if that fixes it, a common enough mistake.

Related

JS to perform calculation based on user input

I have a code where I am trying to calculate a total value based on the value of the input selected by a user. It seems simple but I can't get the total to reflect. Please can someone show me where the fault is?
function calculate() {
var panel = parseInt(document.getElementsById("panel").value);
panelv = 65;
panelt = panel * panelv;
derating_value = 2;
total_hours_standby = panelt * derating_value;
}
document.getElementsById("total_hours").innerHTML = total_hours_standby;
<input type="number" id="panel" placeholder="panel quantity"></input><br>
<button type="button" onclick="calculate">Result</button>
<p id="total_hours">result displays here</p>
You need to
use for onclick="calculate()" take the function call, not only the function,
use getElementById, spelling matter,
declare all variables,
and finally move the output inside of the function
function calculate() {
var panel = parseInt(document.getElementById("panel").value),
panelv = 65,
panelt = panel * panelv,
derating_value = 2,
total_hours_standby = panelt * derating_value;
document.getElementById("total_hours").innerHTML = total_hours_standby;
}
<input type="number" id="panel" placeholder="panel quantity"></input><br>
<button type="button" onclick="calculate()">Result</button>
<p id="total_hours">result displays here</p>
getElementById is singular
declare your vars
call calculate() with brackets
assign the value inside the function
</input> is not needed
Here is a version with eventListeners since other answers already showed you how to fix YOUR version
function calculate() {
var panel = +document.getElementById("panel").value;
if (panel === "" || isNaN(panel)) panel = 0;
let panelv = 65;
let panelt = panel * panelv;
let derating_value = 2;
document.getElementById("total_hours").textContent = (panelt * derating_value);
}
window.addEventListener("load", function() {
document.getElementById("calc").addEventListener("click", calculate)
calculate(); // run at load
})
<input type="number" id="panel" placeholder="panel quantity"><br>
<button type="button" id="calc">Result</button> result displays here: <span id="total_hours"></span>
First, you should call method calculate.
<button type="button" onclick="calculate()">Result</button>
Then, add this line document.getElementsById("total_hours").innerHTML = total_hours_standby; inside calculate function.
Alos, typo error: document.getElementById instead of document.getElementsById
There are couple of issues here:
Most you could have found out if you had looked into console logs.
For starter the function is called getElementById not getElementsById, because there is supposed to be only one element with unique id, so plural does not make sense here.
Another one is a logic error: not updating content after clicking on button i.e when calculate gets executed.
There is also one more syntax error, which is how functions should be passed to HTML element's attribute. It needs to be functionName() instead of functionName
This is how simply fixing this code could look like:
var total_hours_standby = 0;
function calculate() {
var panel = parseInt(document.getElementById("panel").value);
panelv = 65;
panelt = panel * panelv;
derating_value = 2;
total_hours_standby = panelt * derating_value;
document.getElementById("total_hours").innerHTML = total_hours_standby;
}
document.getElementById("total_hours").innerHTML = total_hours_standby;
<input type="number" id="panel" placeholder="panel quantity"></input><br>
<button type="button" onclick="calculate()">Result</button>
<p id="total_hours">result displays here</p>
Here I give you couple of ideas for improving it.
Since you use global variable total_hours_standby it may be a good
idea to encapsulate it. So called module pattern should do the job.
New value of total_hours_standby does not seem to depend on an old
one, so I guess you mean to use it somewhere else - in order to do
so, you need to expose it with "public" getter.
If above is not the case, then you don't need total_hours_standby
variable at all and you can just directly return it or display it
without storing this value in variable.
I put code for rendering in separate function - this is because rule
of thumb for functions is that they should have single
responsibility. One functions for calculations, another for rendering
and then one function for handling user's input and click event, that
uses two previous ones. This way if for example you only want to
calculate something without rendering result, then you just, simply can :)
I also stored DOM nodes in variables, instead of calling
getElementById, it is not due to performance, how it is often
assumed, I did it only for better readability.
Constants instead of hard-coded values.
var Calculator = (function() {
const panelInput = document.getElementById("panel");
const output = document.getElementById("total_hours");
const PANEL_V = 65;
const DERATING_VALUE = 2;
const render = value => output.innerHTML = value;
const calculate = value => value * PANEL_V * DERATING_VALUE;
let total_hours_standby = 0;
return {
handleInput: function() {
total_hours_standby = calculate(panelInput.value);
render(total_hours_standby);
},
getTotalHoursStandby: () => total_hours_standby
};
})();
<input type="number" id="panel" placeholder="Panel quantity" />
<button type="button" onclick="Calculator.handleInput()">Calculate</button>
<p id="total_hours">Result displays here</p>
It is typo,
document.getElementsById
should be
document.getElementById

How to use array fill in javascript showing the text or number inputed by the user?

So one of my assignments is about that I should let the user type whatever he wants and then I have to fill the array with the input from the user, so it's basically could be number/s or text. I don't know if I should use getelementbyid.value or something else.
SO here´s what I have so far:
Fill1();
function Fill1() {
var text1 = document.getElementById("smth").value;
}
function prfunc() {
document.getElementById("answer").innerHTML = Fill1.fill(text1);
}
Type whatever you want: <input type="smth" id="smth"><br>
<button onclick="Fill1()">Fyll</button><br>
<div id="answer"></div>
Rando aside - I believe array.fill doesn't work in IE11, if you have any requirements around browser support. Dunno about any other browsers, just ran into that last week on a project.
Who uses IE11 nowadays? Apparently a few thousand of our customers.
Try
let array = Array(10);
function Fill1() {
array.fill(smth.value)
prfunc();
}
function prfunc() {
answer.innerText = array;
}
Type whatever you want: <input type="smth" id="smth"><br>
<button onclick="Fill1()">Fill</button><br>
<div id="answer"></div>

Why is my increment-er returning an object? id_[object HTMLInputElement]

In my form, I want to offer the ability to add another location. It was working when I had only one text box appear,(address) and could get multiple address text boxes to appear. but now I am trying to add the "city" text-box and it is not working. I used one function before, now I split up my functions to reuse code better. So now my id's (id_) should be id_1,id_2,ect. but I am getting the object instead. I think the addLoc() should be on its own, vs function city() inside function addLoc(), but that wasnt working either.
HTML
<div class="one">
<button onclick="addLoc()">Add Location</button>
</div>
<div class="three">
<h2>Locations</h2>
<form action="#" id="mainform" method="get" name="mainform">
<div id="myForm"></div>
<input type="submit" value="Submit">
</form>
</div>
javaScript
var i = 0;
function increment(){
i += 1;
}
function addLoc(){
var d = document.createElement("DIV");
var l = document.createElement("LABEL");
var i = document.createElement("INPUT");
address();
city();
function address() {
i.setAttribute("type","text");
i.setAttribute("placeholder","Address");
build();
}
function build() {
var g = document.createElement("IMG");
g.setAttribute("src", "delete.png");
increment();
i.setAttribute("Name","textelement_" + i);
d.appendChild(l);
l.setAttribute("for","textelement_" + i);
g.setAttribute("onclick", "removeElement('myForm','id_" + i + "')");
d.appendChild(g);
d.setAttribute("id","id_" + i);
document.getElementById("myForm").appendChild(d);
}
function city() {
i.setAttribute("type","text");
i.setAttribute("placeholder","City");
build();
}
}//end of addLoc()
Here is the jsFiddle (some changes)
was working fine with just the address text box. I broke something trying to split up the functions. I can do it all as one BIG function, but prefer not to.
Any help Much appreciated!
var i = document.createElement("INPUT"); d.setAttribute("id","id_" + i); This is why your id is what it is. To fix it, use a different variable name for your input element.
Looks like you redeclare the variable "i" in your function addLoc() as an input element. Therefore it's not using the "i" you declared at the top of your code outside the function scope (var i = 0;) on line 0. So it's actually trying to append the object to the string which turns out as you see it in your html.
Try not to overload variable names, especially when declaring them outside function scope. If you're going to use global variables, preface them with a marker like g_variableName so they don't get mixed up with function scope variables.
Also, try to use meaningful names for your function variables instead of d,l,i. I would change your input variable them to something like "divElement", "labelElement", "inputElement".
Changing the variable name of 'i' that you declare in the function addLoc() and carrying it through that function should help!

Replace text, and replace it back

I am using this code to replace text on a page when a user clicks the link. I would like a way to replace it back to the initial text using another link within the replaced text, without having to reload the page. I tried simply adding the same script within the replaced text and switching 'place' and 'rep_place' but it didn't work. Any ideas? I am sort of a novice at coding so thanks for any advice.
<div id="place">
Initial text here
<SCRIPT LANGUAGE="JavaScript">
function replaceContentInContainer(target,source) {
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}
</script>
<div class="text" onClick="replaceContentInContainer('place', 'rep_place')">
<u>Link to replace text</u></div></div>
<div id="replacements" style="display:none">
<span id="rep_place">
Replacement text here
</div></span>
Where do you store the original text? Consider what you're doing in some simpler code...
a = 123;
b = 456;
a = b;
// now how do you get the original value of "a"?
You need to store that value somewhere:
a = 123;
b = 456;
temp = a;
a = b;
// to reset "a", set it to "temp"
So in your case, you need to store that content somewhere. It looks like the "source" is a hidden element, it can just as easily hold the replaced value. That way values are swapped, not just copied. Something like this:
function replaceContentInContainer(target,source) {
var temp = document.getElementById(target).innerHTML;
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
document.getElementById(source).innerHTML = temp;
}
So replace them you simply call:
replaceContentInContainer('place', 'rep_place')
Then to swap them back:
replaceContentInContainer('rep_place', 'place')
Note that this will replace the contents of the "source" element until they're swapped back again. From the current code we can't know if that will affect anything else on the page. If so, you might use a different element to store the original values. That could get complex quickly if you have a lot of values that you need to store.
How's this? I store the initial content in an element of an array called initialContent.
<div id="place">
Initial text here [replace]
</div>
<div id="replacements" style="display:none">
<span id="rep_place">
Replacement text here [revert]
</span>
</div>
<SCRIPT LANGUAGE="JavaScript">
var initialContent = [];
function replaceContentInContainer(target,source) {
initialContent[target] = document.getElementById(target).innerHTML;
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}
function showInitialContent(target) {
document.getElementById(target).innerHTML = initialContent[target];
}
</SCRIPT>
Working example: http://jsbin.com/huxodire/1/
The main changes I did were the following:
I used textContent instead of innerHTML because the later replaces the whole DOM contents and that includes removing your link to replace the text. There was no way to generate that event afterwards.
I closed the first div or else all the text would be removed with the innerText including the text that works as a link.
You said you wanted to replace back to the original text, so I used a variable to hold the last value only if this existed.
Hope this helps, let me know if you need more assistance.
The div tags were mixed up and wiping out your link after running it. I just worked with your code and showed how you could switch.
<div id="place">
Initial text here
</div>
<SCRIPT LANGUAGE="JavaScript">
function replaceContentInContainer(target,source) {
document.getElementById(target).innerHTML =
document.getElementById(source).innerHTML;
}
</script>
<div class="text" onClick="replaceContentInContainer('place', 'rep_place')">
<u>Link to replace text</u></div>
<div class="text" onClick="replaceContentInContainer('place', 'original_place')">
<u>Link to restore text</u></div>
<div id="replacements" style="display:none">
<span id="rep_place">
Replacement text here
</span>
<span id="original_place">
Initial text here
</span>
</div>

Pass variable in document.getElementByid in javascript

I have a variable account_number in which account number is stored. now i want to get the value of the element having id as account_number. How to do it in javascript ?
I tried doing document.getElementById(account_number).value, but it is null.
html looks like this :
<input class='transparent' disabled type='text' name='113114234567_name' id='113114234567_name' value = 'Neeloy' style='border:0px;height:25px;font-size:16px;line-height:25px;' />
and the js is :
function getElement()
{
var acc_list = document.forms.editBeneficiary.elements.bene_account_number_edit;
for(var i=0;i<acc_list.length;i++)
{
if(acc_list[i].checked == true)
{
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
alert(document.getElementById("'" + ben_name.toString() + "'").value);
}
}
}
here bene_account_number_edit are the radio buttons.
Thanks
Are you storing just an integer as the element's id attribute? If so, browsers tend to behave in strange ways when looking for an element by an integer id. Try passing account_number.toString(), instead.
If that doesn't work, prepend something like "account_" to the beginning of your elements' id attributes and then call document.getElementById('account_' + account_number).value.
Why are you prefixing and post-fixing ' characters to the name string? ben_name is already a string because you've appended '_name' to the value.
I'd recommend doing a console.log of ben_name just to be sure you're getting the value you expect.
the way to use a variable for document.getElementById is the same as for any other function:
document.getElementById(ben_name);
I don't know why you think it would act any differently.
There is no use of converting ben_name to string because it is already the string.
Concatenation of two string will always give you string.
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
try following code it will work fine
var ben_name=acc_list[i]+ "_name";
here also
alert(document.getElementById("'" + ben_name.toString() + "'").value);
try
alert(document.getElementById(ben_name).value);
I have tested similar type of code which worked correctly. If you are passing variable don't use quotes. What you are doing is passing ben_name.toString() as the value, it will definitely cause an error because it can not find any element with that id viz.(ben_name.toString()). In each function call, you are passing same value i.e. ben_name.toString() which is of course wrong.
I found this page in search for a fix for my issue...
Let's say you have a list of products:
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_1">149.95</p>
add to cart
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_2">139.95</p>
add to cart
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_3">49.95</p>
add to cart
</div>
The designer made all the prices have the digits after the . be superscript. So your choice is to either have the cms spit out the price in 2 parts from the backend and put it back together with <sup> tags around it, or just leave it alone and change it via the DOM. That's what I opted for and here's what I came up with:
window.onload = function() {
var pricelist = document.getElementsByClassName("rel-prod-price");
var price_id = "";
for (var b = 1; b <= pricelist.length; b++) {
var price_id = "price_format_" + b;
var price_original = document.getElementById(price_id).innerHTML;
var price_parts = price_original.split(".");
var formatted_price = price_parts[0] + ".<b>" + price_parts[1] + "</b>";
document.getElementById(price_id).innerHTML = formatted_price;
}
}
And here's the CSS I used:
.rel-prod-item p.rel-prod-price b {
font-size: 50%;
position: relative;
top: -4px;
}
I hope this helps someone keep all their hair :-)
Here's a screenshot of the finished product

Categories