Want to output a visual price - javascript

ok, I've spent the past 5 hours trying to codge together a small javascript code for a website.
Basically the widths are set values of 2 or 4 (which the user will use a simple drop-down option).
Length can be anything from 1 to 60.
The price will be a fixed price, so can just be hidden out of the way.
Now this is where I start to go South with the situation, I'm having problems spitting the result out into a div area on the page, this is what I have so far;
<script type="text/javascript">
function only_numbers(value){
var check_this = value;
var expression = /^\d*\.*\d*$/;
if(expression.test(check_this)){ return true; }
else{ return false; }
}
function calculate(){
var lengthVal = document.mult.lengthVal.value;
var heightVal = document.mult.heightVal.value;
var priceVal = document.mult.priceVal.value
var showValue = 0;
if(only_numbers(lengthVal) && only_numbers(heightVal) && only_numbers(priceVal)){
var showValue = ((lengthVal * heightVal) * 1.25) * priceVal;
// showValue = Math.round(showValue * 100) / 100;
document.getElementById('showValue').innerHTML = "showValue";
}else{
alert("Please enter only numerical values.");
}
}
</script>
</head>
<body>
<form name="mult">
Length: <input type="text" name="lengthVal" /> <br />
Height: <input type="text" name="heightVal" /> <br />
Price: <input type="text" name="priceVal" /> <br />
<input type="button" value="Calculate" onClick="calculate()" />
</form>
<div id="showValue"></div>
I know I've not sorted the price out to be hidden and is just an open variable atm, please guys, any help would be great.

document.getElementById('showValue').innerHTML = "showValue";
You probably want to write your variable value in there, not the string "showValue". So you should be using:
document.getElementById('showValue').innerHTML = showValue;

Related

Basic math functions in JavaScript to show on HTML page

I would like to make major of basic math functions (addition, subtraction, ect.) to develop in JavaScript. Input parameters should be from HTML webpage, than do the in JavaScript and return result on the same HTML page.
function math() {
//document.getElementById("frm1").innerHTML;
var numb = document.getElementById("number").innerHTML;
var mod = document.getElementById("modifier").innerHTML;
console.log(numb);
console.log(mod);
var sum = 1; //numb + mod; //the 1 is a placeholder
console.log(sum);
sum = document.getElementById("sum").innerHTML;
}
<form id="frm1" action="randScript.js">
Number: <input type="int" name="number" id="number"><br> Modifiers: <input type="int" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id="sum"></p>
Your form tag has an action attribute. This means the page will submit your information to the specified page. You can use jQuery to prevent the form from submitting.
$("#yourFormId").on("submit",function(event){event.preventDefault()})
You can also edit the forms action attribute itself to prevent it from submitting.
<form id="frm1" action"javascript:void(0);">
First: The type is text - there is no "int" thing
Number: <input type="text" name="number" id="number">
Second: if we read a bit documentation we figure also out how to get the alue into the JS part
var numb = document.getElementById("number").value;
here you can now do your further homework ;)
Third: Get things back:
either use another input. They work two ways.
document.getElementById("result").value="I did not do my homework alone"
or you place a div somewhere with an id
<div id="result"> </div>
and now you can really use innerHTML in js
document.getElementById("result").innerHTML="I am too lazy";
The rest and to put it all together is now up to you :) Have fun to study :)
Try that if you want to display the sum at the html element:
document.getElementById("sum").innerHTML = sum;
But a more precise Question would help!
There is no int type for form inputs in HTML you can learn here about input types: HTML form input types
<form id="frm1" >
Number1: <input type="number" name="number" id="number1"><br>
Number2: <input type="number" name="number" id="number2"><br>
Modifiers: <input type="text" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id = "sum"></p>
<script type="text/javascript">
function math() {
var numb1 = parseInt(document.getElementById("number1").value);
var numb2 = parseInt(document.getElementById("number2").value);
var mod = document.getElementById("modifier").value;
if(mod == '+'){
var sum = numb1 + numb2;
}else if(mod == '-'){
var sum = numb1 - numb2;
}else if(mod == '*'){
var sum = numb1 * numb2;
}
if(sum === undefined){
alert('invalid inputs');
return false;
}else{
document.getElementById("sum").innerHTML = sum;
}
return true;
}
To retrieve inputs values properly use value rather then innerHtml.
Retrieved values are strings so you need to parse them to numbers (with parseInt) before using them in math.
function math() {
const numb = document.getElementById("number").value;
const mod = document.getElementById("modifier").value;
sum = document.getElementById("sum").innerText = parseInt(numb) + parseInt(mod);
}

oninput and onchange not working because of bad coding

My code is here. Below is the HTML:
<!DOCTYPE html>
<html>
<title>Electricity and Magnetism Demo</title>
<body>
<p>
<label>Voltage:</label>
<input id="inputVoltage" type="number" oninput="EqualsVoltage()" onchange="EqualsVoltage()"> </p>
<p>
<label>Current:</label>
<input id="inputCurrent" type="number" oninput="EqualsCurrent()" onchange="EqualsCurrent()"> </p>
<p>
<label>Resistance:</label>
<input id="inputResistance" type="number" oninput="EqualsResistance()" onchange="EqualsResistance()"> </p>
<script language="Javascript" type="text/javascript" src="EandM.js"></script>
</body>
</html>
Here is the Javascript:
//Electricity and Magnetism Stuff
function EqualsVoltage() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
document.getElementById("inputVoltage").value = (Current * Resistance);
}
function EqualsCurrent() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
document.getElementById("inputCurrent").value = (Voltage / Resistance);
}
function EqualsResistance() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
document.getElementById("inputResistance").value = (Voltage / Current);
}
I want my calculator to react to both oninput and onchange events when I change a value in the text field.
I've been able to make a converter that converts kilometers to miles when oninput and onchange were functioning; however, I can't figure this out.
When I enter data in the field, it doesn't change the other values. Please help!
The problem: when user edit e.g. voltage in input then calculations at the same time change that input value (the input values and calculated values are usually different). Solution: show output calculations in separate place - not as input values. When you use oninput you don't need to use onchange.
function calc() {
let c = inputCurrent.value;
let r = inputResistance.value;
let v = inputVoltage.value;
msg.innerHTML = `voltage: ${ c*r } <br>`
+ `current: ${ v/r } <br>`
+ `resistance: ${ v/c } <br>`;
}
<p>
<label>Voltage:</label>
<input id="inputVoltage" type="number" oninput="calc()">
</p>
<p>
<label>Current:</label>
<input id="inputCurrent" type="number" oninput="calc()">
</p>
<p>
<label>Resistance:</label>
<input id="inputResistance" type="number" oninput="calc()">
</p>
Calculations:
<div id="msg"></div>
This works. Should have been checking the other text boxes not the current one. It will keep changing the fields as the user increases or decreases the value.
<!DOCTYPE html>
<html>
<title>Electricity and Magnetism Demo</title>
<head>
<script type="text/javascript">
function EqualsVoltage() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
if(Resistance != "0" && Current != "0" ){
document.getElementById("inputVoltage").value = (Current * Resistance);
}
}
function EqualsCurrent() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
if(Voltage != "0" && Resistance != "0" ){
document.getElementById("inputCurrent").value = (Voltage / Resistance);
}
}
function EqualsResistance() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
if(Voltage != "0" && Current != "0" ){
document.getElementById("inputResistance").value = (Voltage / Current);
}
}
</script>
</head>
<body>
<p>
<label>Voltage:</label>
<input id="inputVoltage" type="number" oninput="EqualsResistance(); EqualsCurrent()" value="0"> </p>
<p>
<label>Current:</label>
<input id="inputCurrent" type="number" oninput="EqualsVoltage(); EqualsResistance()" value="0"> </p>
<p>
<label>Resistance:</label>
<input id="inputResistance" type="number" oninput="EqualsCurrent();EqualsVoltage()" value="0"> </p>
</body>
</html>
There is already a great answer you can take, but I wanted to provide you an alternative. It's up to you which one fits better to your needs.
This solution provides an alternative for the user to decide when to calculate the values. This can avoid unexpected values as Infinity, 0, etc..
For this, you could give a button to every element in order to let the user click the one he wants the result for. This will update the value to the input box where he presses the button. The button would look like this:
<p>
<label>Resistance:</label>
<input id="inputResistance" type="number">
<button id="calcResistance"><!-- Add this to every input -->
Calc
</button>
</p>
And your JavaScript code will look like this:
function updateValues(e) {
let changed = e.target.id,
Voltage = Number(document.getElementById('inputVoltage').value),
Current = Number(document.getElementById("inputCurrent").value),
Resistance = Number(document.getElementById('inputResistance').value);
switch(changed){
case "calcResistance":
document.getElementById("inputResistance").value = (Voltage / Current);
break;
case "calcVoltage":
document.getElementById("inputVoltage").value = (Current * Resistance);
break;
case "calcCurrent":
document.getElementById("inputCurrent").value = Voltage / Resistance;
break;
}
}
document.querySelectorAll("button").forEach(b=>b.addEventListener("click",updateValues));
I hope this gives you another way to achieve what you want.
Here is a fiddle of what I am talking about:
function updateValues(e) {
let changed = e.target.id,
Voltage = Number(document.getElementById('inputVoltage').value),
Current = Number(document.getElementById("inputCurrent").value),
Resistance = Number(document.getElementById('inputResistance').value);
switch(changed){
case "calcResistance":
document.getElementById("inputResistance").value = (Voltage / Current);
break;
case "calcVoltage":
document.getElementById("inputVoltage").value = (Current * Resistance);
break;
case "calcCurrent":
document.getElementById("inputCurrent").value = Voltage / Resistance;
break;
}
}
document.querySelectorAll("button").forEach(b=>b.addEventListener("click",updateValues));
<p>
<label>Voltage:</label>
<input id="inputVoltage" type="number">
<button id="calcVoltage">
Calc
</button></p>
<p>
<label>Current:</label>
<input id="inputCurrent" type="number">
<button id="calcCurrent">
Calc
</button></p>
<p>
<label>Resistance:</label>
<input id="inputResistance" type="number">
<button id="calcResistance">
Calc
</button></p>
I would recommend using onkeyup instead of onchange and oninput. [edit] Wont work with the buttons, however.
I'm guessing the workflow is "When I enter something two number fields, the third one is calculated".
But what happens then if all three text fields are filled in?
If you filled in voltage, current, and resistance, and then change voltage again, should current or resistance change?
You need to think about workflow before you do any coding, and that's why the code is wrong.

Limiting Text Input Based On Another Text Input

It seems pretty simple but I can't find a good way to do it.
I am doing a research bar which allow users to search something in terms of price mini and price maxi.
So :
I have two text input types (in html of course) "price_mini?" and "price_maxi?".
"Price_mini" cannot be bigger than "price_maxi".
How can I limit the users input of "price_mini" so that if does not allow the user to enter more than the "price_maxi" variable's input and then display an error on save(search) if the mini number is bigger than price_maxi.
Something like this should work, I couldn't get JSFiddle to handle the form to show you a good example and I don't do much in plain javascript now in days so pardon me if there is a small error or two.
HTML
<form name="myForm" onSubmit="submit()" method="post">
<input name="price_mini" type="text">
<input name="price_maxi" type="text">
<input type="submit" value="Submit">
</form>
Javascript
function submit(){
var price_mini = document.forms["myForm"]["price_mini"].value;
var price_maxi = document.forms["myForm"]["price_maxi"].value;
if(Number(price_mini) > Number(price_maxi)){
alert("Minimum price must be less than maximum price!");
}else{
// Your search code here
}
}
Imagine this html
<input id="min" type="text">
<input id="max" type="text">
This should be the correct javascript
var min = document.getElementById("min");
var max = document.getElementById("max");
min.change(function() {
if(Number(this.value) > Number(max.value)) {
this.value = max.value; // replace min with the same max value if it's bigger
}
}
Let's assume that this is your HTML.
<input id="min" type="text">
<input id="max" type="text">
The working JavaScript is this with the behavior if the max field is empty.
var min = document.querySelector('#min');
var max = document.querySelector('#max');
var calculate = function() {
if(max.value == '') return;
if(Number(min.value) > Number(max.value)) {
min.value = max.value;
}
}
min.addEventListener('input', calculate);
max.addEventListener('input', calculate);
You should compare them when they have value (min && max). If you notice that min is higher you can alert to the user or change it automatically to the lowest or to the highest.
$('.calc_input').change( function() {
var min = $('#min').val();
var max = $('#max').val();
if ( (min && max) && min > max ) {
alert('This can not be!');
// $('#min').val() = max;
// $('#max').val() = min;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Min:<input id="min" class="calc_input">
<br>
Max:<input id="max" class="calc_input">

Grab form fields and calculate based on inputs

I'm getting an undefined error and don't know why this isn't working.
It's supposed to divide the rent by the amount of roommates:
function splitRent() {
var roommates = document.getElementById("rent");
var rent = document.getElementById("rent");
var rentEach = rent / roommates;
if (document.getElementById("submit") == true) {
document.write("You each should pay" + " " + rentEach)
} else {
document.alert("Gimme info")
}
};
<h1>Roommate Room Splitter</h1>
<form id="myForm">
Roommates:
<input type="text" name="roommates" id="roommates">
<br/>Rent:
<input type="text" name="rent" id="rent">
<br/>
<input type='submit' id='submit' value='Submit' onclick="splitRent()" />
</form>
You want to take the value of the fields, not the fields themselves.
document.getElementById() returns the node, but you want the value of the input field:
var rent = document.getElementById("rent").value;
Also, you're getting the value of the rent twice; you want to check the roommates as well.
var roommates = document.getElementById("roommates").value;
Lastly, document.getElementById("submit") == true doesn't mean anything: you're comparing a button node with a boolean value, which doesn't make sense. If you want to check to make sure that both fields are filled, try this:
if(roommates && rent){
//do calculations
}else{
window.alert("Enter something"); //note that it's window.alert(), not document.alert(), which is not a function
As it stands, this allows people to enter things that are not numbers; there are two things that you could do to fix that.
Use parseInt()/parseFloat() to ensure that you're extracting a number
Check that you actually have a number before doing calculations
You'd do something like this:
var rent = parseInt(document.getElementById("rent").value);
var roommates = parseFloat(document.getElementById("rooommates").value);
If you use the checking I've done above (rent && roommates), the validation will take place there (it checks for both empty and NaN values).
function splitRent() {
var roommates = parseInt(document.getElementById("roommates").value);
var rent = parseFloat(document.getElementById("rent").value);
var rentEach = rent / roommates;
if (roommates && rent) {
document.write("You each should pay" + " " + rentEach)
} else {
window.alert("Gimme info")
}
};
<h1>Roommate Room Splitter</h1>
<form id="myForm">
Roommates:
<input type="text" name="roommates" id="roommates">
<br/>Rent:
<input type="text" name="rent" id="rent">
<br/>
<input type='submit' id='submit' value='Submit' onclick="splitRent()" />
</form>
Shouldn't this be:
var roommates = document.getElementById("roommates").value;
var rent = document.getElementById("rent").value;
Do you always get "1" for your result?

How to get auto + javascript input fields

I'm trying to get an autosum from fields, the issue is that if the total of fields are without value the script is not working correctly, and also if there are more than 7 fields again the script is not working.
here is the javascript:
function getTotal()
{
var value01 = document.getElementById('value01').value;
var value02 = document.getElementById('value02').value;
var value03 = document.getElementById('value03').value;
var value04 = document.getElementById('value04').value;
var value05 = document.getElementById('value05').value;
var value06 = document.getElementById('value06').value;
var value07 = document.getElementById('value07').value;
// Add them together and display
var sum = parseInt(value01) + parseInt(value02) + parseInt(value03) + parseInt(value04) + parseInt(value05) + parseInt(value06) + parseInt(value07);
document.getElementById('sum_total').value = sum;
}
inputs:
<input type="text" id="value01" />
<input type="text" id="value02" />
<input type="text" id="value03" />
here is starting to be added with a button more input fields.
<input type="text" id="+" />
<input type="text" id="++" />
<input type="button" value="Add Them Together" onclick="getTotal();" />
my question is, how can i get an auto + on var value01 02 03 etc.
Any help is appreciated.
Your question is not very clear and so I'm not too sure what you are wanting to do so feel free to offer clarification for optimum assistance. On that note, based off of what you have provided, I have two things to point out:
1) Your ID of "+" is not valid. Per the HTML 4 spec:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be
followed by any number of letters, digits ([0-9]), hyphens ("-"),
underscores ("_"), colons (":"), and periods (".").
2) Instead of creating a different var containing each value, I would recommend creating a function that you can use within a for loop that will determine the sums of each incremental input. This is more DRY and helps simplify things if the number of inputs were to grow.
function getValues(id){
return document.getElementById(id).value;
}
The pure JavaScript solution below begins with one input box and will add additional inputs with the click of a button, which I believe is what you're looking for. You can modify the number of initial input boxes accordingly, but it should give you an idea.
Javascript:
var max = 1;
function getValues(id){
var result = document.getElementById(id).value;
return (result ? result : 0);
}
function addInput(){
max++;
var input = '<input type="text" id="value'+ max +'" />';
document.getElementById("valuesContainer").innerHTML += input;
}
function getTotal(){
var sum = 0;
for(var i=1; i <= max; i++){
sum = sum + parseFloat(getValues("value" + i));
}
document.getElementById("total").innerHTML = sum;
}
HTML:
<div id="valuesContainer">
<input type="text" id="value1" />
</div>
<input type="button" value="Add Value" id="addMore" onclick="addInput();" />
<input type="button" value="Calculate Total" onclick="getTotal();" />
<div id="total"></div>
Demo: http://jsfiddle.net/Y4xgU/

Categories

Resources