jQuery prepopulate form fields from select box and calculate results - javascript

I am building a calculator form to allow people to calculate the cost of running electrical appliances. They can select an appliance, as an example, from a dropdown list and this should prepopulate the text fields with the figures necessary for the calculation. Here is the form:
<form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method = "POST">
<label>Appliance</label>
<select id="list" >
<option value="select">Select</option>
<option value="dishwasher">Dishwasher</option>
<option value="iron">Iron</option>
</select>
<label>Watts</label> <input name="watts" /><br>
<label>Hours</label> <input name="hours" /> <br>
<label>Price</label> <input name="price" /> <br>
<label>Number</label> <input name="number" /> <br>
<label>Total</label> <input name="total" value="" id="total"></input>
</form>
When a user selects an appliance I want the input fields to be filled something like this:
case 'dishwasher':
$('input[name="watts"]').val('1200');
$('input[name="hours"]').val('20');
$('input[name="price"]').val('10');
$('input[name="number"]').val('1');
Then do some calculation on the figures:
kilowatts = watts / 1000;
kwhours = kilowatts * hours;
costpounds = kwhours * price / 100;
total = costpounds * number
and put the total into the total field in the form, the idea is to also allow the user to change the figures, or even just add their own, in the form and the total updates accordingly. I can get all the individual bits to work, but don't know jquery well enough to put it all together. Help would be greatly appreciated. Thanks!

Here is some javascript / jquery to get you started. There are more efficient ways, but those are very confusing for someone just learning.
//when the document is finished being rendered, this fires
$(document).ready(function(){
//if the user changes the value in the select dd, this fires.
$('#list').change(function(e){
changeInputValues(this.val());
});
// standard JS function to set the input values with defaults for a given drop down. your idea ;)
function changeInputValues(ddValue){
//put your Case 'dishwasher' code here, one case for each Drop down value
//$('input[name="watts"]').val('1200');
//$('input[name="hours"]').val('20');
//$('input[name="price"]').val('10');
//$('input[name="number"]').val('1');
//recalculate the figures
recalculate();
};
// when someone changes an input, but not the Drop Down, we have that on already.
$('input').not('select').change(function(e){
recalculate();
});
function recalculate(){
// get the current values, then do your math
//var currentWatts = $('input[name="watts"]').val();
//var currentHours = $('input[name="hours"]').val();
//....
//var total = 0;
// do more math... whatever you want
//set the 'visible' value
$('input[name="total"]').val(total)
};
});

So basic structure is 2 functions.
Called when the "appliance" select is changed. Takes all the values of the item selected by grabbing the id like $(this)find('selected').attr('id')*. Once you have the id of the select appliance you can use it to pull the correct values from your appliance arrays and then it's easy to $(this).find('name_of_filed').text("value from the array") with a little for each loop.
called when any other field is onChanged (or you can make an update button in case it's annoying to have it constantly updating while you are making multiple changes). Also called at the end of function 1. Takes all the values from the fields, does calculation, inserts into "total" field.
you can certainly break this down much further to smaller pieces if you want it to be more easily edited in the future and to reuse any of this code but if it's going to be a one of then I wouldn't bother splitting it much more than this.
I can get a lot more specific if need be but I figure it's better for you to try and figure specifics out to learn as you go and we here at SO can answer specific questions as you go.
*may not be actuall correct code. I'm lazy and you will learn more this way! ;)

Related

How do I replace an HTML element on click?

I am developing this code for a storytelling type game and I need to change the dropbox options after the user or player is done selecting their option. I am trying to make the options in the dropbox relevant to what is happening in the game at the given moment. I was told to do research on a possible change of element(with different options in the dropbox) every time the user has chosen their option.
I have tried some jquery, but only moved the dropbox on click. I could not find any type of operator that could help me with changing it. The append bit in my code is submitting the input and getting an outcome
<div id="actions">
<select id="chosen_action">
<option value="You have entered the dungeon...">Yes</option>
<option value="You turned and left THE END">No</option>
<option value="You attempted to communicate with the enemy...">Talk</option>
</select>
<button onclick="append_to_history()">Go!</button>
</div>
You can do this really easily with .innerHTML:
$("#chosen_action").innerHTML = `
<option>You turn away from the castle</option>
<option>You take a closer look at the old drawbridge</option>
<option>You decide to consult your map</option>
`;
.innerHTML simply changes the HTML content of a given element. The backtick operators (`) form a template string, which is capable of spanning multiple lines, making it easier to lay out your new options. You could use a regular string here instead if you'd like (and of course can generate this value with a loop, array, etc).
const choice = document.getElementById('chosen_action');
const opt1 = document.getElementById('option1');
const opt2 = document.getElementById('option2');
const opt3 = document.getElementById('option3');
const go = document.getElementById('goButton');
go.addEventListener('click',(e) => {
if(choice.value !== ""){
if(choice.value === opt1.value){
opt1.value = ... //change the value of this element
opt2.value = ...
opt3.value = ...
//if need to change value of text shown to user for selection you can:
opt1.textContent = ...//change the text of this element
opt2.textContent = ...
opt3.textContent = ...
} else if(choice.value === opt2.value){
...
...
...
} else{
...
...
...
}
} else {
alert("You must make a choice to continue!")
}
})
<div id="actions">
<select id="chosen_action">
<option id="option1" value="You have entered the dungeon...">Yes</option>
<option id="option2" value="You turned and left THE END">No</option>
<option id="option3" value="You attempted to communicate with the enemy...">Talk</option>
</select>
<button id="goButton" onclick="append_to_history()">Go!</button>
</div>
I can't comment to gather more information, so, without knowing more about what you are asking, or where your game is going, or what "append_to_history()" does, or how many possible combinations there are, etc., this is one way of doing what you need to do.
In the end, I would guess you will have to make a giant object, or a great deal of smaller objects, and come up with a naming system that you can programmatically grab the proper values from when it comes time. Probably a tracker to count the number of choices (each button click) and then name your objects accordingly, so that you can use the tracker value and the option number to call the correct value. You will have to figure out, at some point, every single possible value and then programmatically call them for each new value depending on the value chosen at time of click.
Would be interested to know if anyone else has any different perspective on this, though!

ng-model misbehaving with HTML reset method

Im trying to be as ellaborative as i can with my question....
Scenario:
I have three input fields in my html page Two of them are to accept user inputted values and the third one binds(adds) these two values.
Done so far:
I initially used <input value="{{value1+value2}}" id="value3"/> which took the values as string; solved this issue by substracting the string by 0. But, this calculated values wont go off even using the reset button.
Then someone here on SOF told me to use <input ng-model="(value1-0)+(value2-0)" id="value3"/> which works, but i noticed that even though the values disapper visually the model still holds some value.
(When, i enter some value into the first input field, the third calculated field add the value of the inputted field with the previous value of the second input field(value that the second field had previous to the reset)
NOTE:
Reset method resets the values of the first two user inputted fields, but not that of the third calcualtion field while using <input value="{{value1+value2}}" id="value3"/> OR <input ng-bind="value1+value2" id="value3"/>
While, when using <input ng-model="(value1-0)+(value2-0)" id="value3"/> the calculated field is visually cleared but when i enter some value into one of the user inputted fields(value1 or value2) the calculated field adds the entered number with the previous number that the field ccontained.
I tried many ways to solve this issue, but with no suuccess.... can someone please guide me through?
Thanks in advance.....
Here's a simple fiddle . Follow the link and take a look.
Basically, to have only number values in the user inputed fields, I used HTML5 number inputs, readily available in any newer browser.
<div ng-controller="MyCtrl">
<input type="number" ng-model="value1" />
<input type="number" ng-model="value2" />
<input type="text" ng-model="value1 + value2" />
<button type="button" ng-click="reset()">RESET</button>
</div>
And as for the javascript, here is my controller:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', MyCtrl)
function MyCtrl($scope) {
$scope.value1 = '';
$scope.value2 = '';
$scope.value3 = '';
$scope.reset = function() {
$scope.value1 = '';
$scope.value2 = '';
$scope.value3 = '';
};
}
The three values are first initialized as empty strings, and on ng-click of the RESET button, they are nullified again.
NOTE: For the sake of simplicity I used number inputs instead of trying to implement some kind of javascript validation which I would suggest for production level. The point of my answer was just to explain the principle using the most basic concepts.

Calculations based on radio button choices

I am using a MEAN stack for my web project. The front end is a simple registration form that asks for several user inputs. For example, it says "how many products are you buying?" The next question is a radio button. It says is this product large or small? My question is the following: the calculation to get the cost of the order is #products*42+(12 if large is selected) or #products*42+(0 if small is selected). How do I code this in javascript(I am using node in my backend). In other words, how do I tell my calculation code that when user selects a radio button you need to add a following number and how do I pass on the number of products typed to my formulas? I have started by assigning value=1 for small and value=2 for large radio button option. Just a general example would be helpful as I can code the details and update the formulas once I get around this problem. Thank you
If you want to do the calculation on the client side and the elements are in an HTML form like:
<h1>Radio Buttons</h1>
<form name="catch-radio" method="post">
<div class="input">
<span class="label">How many products are you buying?</span>
<input id="product-count" type="text" name="product_count" value="0"/>
<br/>
<span class="label">Is this product large or small?</span>
<br/>
<span class="label">Large</span>
<input type="radio" name="product-size" value="12" checked="checked"/>
<br/>
<span class="label">Small</span>
<input type="radio" name="product-size" value="0"/>
</div>
</form>
<div>
<h2>Cost of order:</h2>
<p id="calculation"></p>
</div>
with an input for the number of products (with an id of 'product-count') and radio buttons corresponding to the product size (named 'product-size'), you can calculate the cost and output it to an element on the page (with an id of 'calculation') by adding event handlers to the form fields to register a change in the form, and then from those handlers calling a function to perform the calculation and update the page accordingly like so:
// Cost is the count of products purchased multipled by 42 then added
// to 12 in the case that the product is large, and zero in the case
// that the product is small
function calculate_cost() {
let count = parseInt(document.getElementById('product-count').value);
if (count > 0) {
let size = 0;
for (var i = 0 ; i < document.getElementsByName('product-size').length; i++) {
if (document.getElementsByName('product-size')[i].checked) {
size = parseInt( document.getElementsByName('product-size')[i].value);
break;
}
}
let cost = count * 42 + size
document.getElementById('calculation').innerHTML = cost;
}
}
// handlers for form input change
// call calculate_cost() on change
// note that the text input is an on-change event but for radio buttons
// an onclick handler is needed for each button
for (var i = 0 ; i < document.getElementsByName('product-size').length; i++) {
document.getElementsByName('product-size')[i].onclick = function() {
calculate_cost();
}
}
document.getElementById('product-count').onchange = function() {
calculate_cost();
}
I put up a quick demo of this on CodePen here: http://codepen.io/P1xt/pen/yOKqXP/
The particularly interesting bit is that for the radio buttons, you need to add a click handler for each button separately (and it must be a click not a change handler, and to figure out which radio is currently selected, you need to explicitly check each one to see if it's 'checked'.
Note: If you're looking to do your calculations on the server-side, you'd need to submit the form, then collect the product-count and product-size from the submitted form elements in order to perform the calculation.
Why not use 0 and 12 as the values for the radio buttons, then the backend can just add the selected value?

Form Code with Javascript Real Time Calculation

I have been looking for awhile but can not figure how to code the below example:
Enter in Weight of Cans:
(ADD BUTTON) - Purpose to add another input field to enter in additional weight field
Input Field = Weight 1 = 5
Input Field = Weight 2 = 5
Input Field = Weight 3 = 10
Input Field = Weight i = ? (after clicking on ADD)
Then I want in real time for the Total Weight to be calculated so in this case it would be 20 and finaly an estimate of Total Cans with this formula (Total Weight * 150) so in the example Total Cans would be 3000.
I want to use HTML Form and Javascript but I do not know how to handle the Add Button feature so the Total Weight and Total Cans can be calcualted in real time. I am thinking of an array but can not figure the syntax.
Any advice or assistance would be greatly appreicated.
I'm normally against this, but it seems as though you genuinely need help, so here it is. Keep in mind, this is very basic and there are better ways to do this, but I wanted to keep it very simple for you since you're just starting out. First - you really don't need a button. If you want a button, you can assign the function to a button action, but this code automatically calculates the total for you. Also, you'll want to add in some validation, this quick example assumes that everyone always just enters a number like they're supposed to... which never happens, so you'll want to look into some validation as well.
Here is a working example: http://jsfiddle.net/813dL6d3/1/
And the code:
HTML:
<input type="text" id="weight1" onblur="calculateForm();" /><br />
<input type="text" id="weight2" onblur="calculateForm();" /><br />
<input type="text" id="weight3" onblur="calculateForm();" /><br />
<input type="text" id="weightTotal" />
Javascript:
var calculateForm = function () {
document.getElementById("weightTotal").value =
(
Number(document.getElementById("weight1").value) +
Number(document.getElementById("weight2").value) +
Number(document.getElementById("weight3").value)
) * 150;
};

Can I change dyanmic javascript variable depending on user form input?

My question here is if there is a way to change the dynamic price calculation depending on the name a user enters in the input field.
I have code that works very well for calculating a dynamic price in an html form. Here is the code:
Using this input:
<input class="typeahead" type="text" placeholder="Amount" name="Amount"/>
My Javascript then calculates price:
jQuery("input[name='Amount']").change(function () {
if (isNaN(parseFloat(this.value)) || !isFinite(this.value)) {
jQuery(this).val('');
return false;
}
var calc = parseFloat(this.value) * 0.95;
jQuery(this).parents("form").find("input[name='price']").val(calc);
});
That by itself works fantastic. It calculates the amount by .95 and then assigns that value as price.
If I add this into the form:
<input class="stores typeahead" type="text" placeholder="Stores" name="name"/>
What can I do here to be able to calculate the price at different values depending on the store name. For example, if someone enters McDonalds, I want it to calculate at .90. If someone enters Target, I want it to calculate at .92. The previous javascript cannot accomplish this because it calculates everything at .95 instead of being able to change depending on the store entered.
I would prefer to accomplish this with javascript because I'm not very skilled with php.
You can create a Javascript object for this.
var stores = {
"McDonalds" : .90,
"Target" : .92,
}
var storeName = jQuery(this).parents("form").find("input[name='name']").val();
console.log(stores[storeName]); //Output the store cost to console.
Though I think the jQuery lookup function is questionable. I'm sure there is a better way to select that textbox. But that's the general concept you're looking for.

Categories

Resources