I managed to grab all calculated values on group of div and set the total, but they want to only show the lookup value to be showed. currently I showing the calculation on SPAN.
The var "multiplier"
I try to get all input values and set them using below code.
function getInputs(selector) {
var inputs = 0;
$(selector).each(function() {
$(this).find("input").each(function() {
sum += parseInt($(this).html());
$('#').val(parseInt($(this).html()));
var multiplier = $(`table#${tableToUse} tbody > tr[product='${currentProductId}'] > td[volume='${volume}']`).text();
// $('#GrandTotal').val(sum); // give the final sum from Log
});
});
return sum;
}
On the below codepen: https://codepen.io/dunya/pen/mojKNz
I am writing the final sum without any issues.
I would like to show the variable multiplier only.
I need hide the value=10 from user but show the variable multiplier.
My formula is like this:
the lookup value based on Product Origin, Geographical and Volume get the multiplier(as Var) I am getting that value:
sum for single input =multiplier * input value(example for apple it is 10)
I just need to overwrite the input value with multiplier(as Var) for all 10 input fields, I tried using function still not get to far,
any suggestion or how to do it.
thanks.
<div>
<label class="description" for="Apple">Apple</label>
<input id="Apple" name="Apple" class="element text medium" type="text" maxlength="255" value="10" readonly="true"/>
</div>
As you can see on above codepen link, I have ten ID's such as Apple,Apricot .. so on, I make it read only. each has default value for Apple it is 10 and Apricot is 20 it is changing value, I also make it read only to proven end user to change it. my requirement change changed I will need show the value multiplier variable there instead of the attribute value such 10 or 20 so on, problem is I am using value attribute to make the calculation work otherwise my final Grand Total calculation will be wrong. How can I resolve this.
for example I selected Product Origin: Europe, Location: blank and Volume= 10, this 3 drop down gets me the look up table id called "Europe". the Volume will match to the columns to calculate for apple it will 0.1 * 10 (default value for id=Apple is 10) so it gets me 1 so on, Grand Total is Sums all calculated results on SPAN to give final value.
How can still use or store the default value for each input such as 10 so on but replace with multiplier(as Var) such the 10 input will display Apple 0.1, Apricot 0, ... and Coconut 0.1, also remember the default value?
the mock-up shows on image below:
Many thanks
I'm using this answer to check if I got your question right so it will likely not be final!
Setting the Value of an input
If your problem is actually changing the input here are some simple examples:
// ****
// ** WITH JAVASCRIPT ** //
// ****
// Get DOM Elements
const js_input_foo = document.getElementById('js_input_foo');
const js_btn_change = document.getElementById('js_btn_change');
// Add event listener
js_btn_change.addEventListener('click', () => {
js_input_foo.value = 'New Value';
});
// ****
// ** WITH JQuery ** //
// ****
// Get DOM Elements
const jq_input_foo = $('#jq_input_foo');
const jq_btn_change = $('#jq_btn_change');
// Add event listener
jq_btn_change.click(() => {
jq_input_foo.val('New Value');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--
** WITH JAVASCRIPT **
-->
<h2>JavaScript</h2>
<!-- Input which displays a value -->
<input id="js_input_foo" type="text" value="100" />
<!-- Button which changes the input -->
<button id="js_btn_change">Change!</button>
<!--
** WITH JAVASCRIPT **
-->
<h2>JQuery</h2>
<!-- Input which displays a value -->
<input id="jq_input_foo" type="text" value="100" />
<!-- Button which changes the input -->
<button id="jq_btn_change">Change!</button>
Setting the value of an input according to dataset
If you want to set your inputs with looping through them this could help:
// Constants
const dataset = {
one: "new date one",
two: "new date two",
three: "new date three",
four: "new date four",
five: "new date five"
};
// Dom elements
const container_inputs = document.getElementById('container_inputs');
const btn_changeInputs = document.getElementById('btn_changeInputs');
// Add Event Listener
btn_changeInputs.addEventListener('click', () => {
Array.from(container_inputs.children).forEach(child => {
let key = child.getAttribute('key'); // Get the Key Attribute
// If key attribute exists fill the corresponding entry
if(key) child.value = dataset[key];
});
});
<h2>Setting the corresponding values</h2>
<div id="container_inputs">
Input One <input type="text" id="input_one" key="one"> <br>
Input Two <input type="text" id="input_two" key="two"> <br>
Input Three <input type="text" id="input_three" key="three"> <br>
Input Four <input type="text" id="input_four" key="four"> <br>
Input Five <input type="text" id="input_five" key="five">
</div>
<button id="btn_changeInputs">Change!</button>
Getting an attribute and use it in calculations for value
So setting the value of an element dependent of an attribute and multiplier would then be:
// **
// JavaScript
// **
element.value = element.getAttribute('my_value') * multiplier;
// **
// JQuery
// **
// ****************************************************
// I STRONGLY RECOMMEND ONLY GETTING THE ELEMENT ONCE *
// ****************************************************
let element = $('#element'); // Getting the element
element.val(element.attr('my_value') * multiplier); // Setting the value
And the html element would look like:
<input type="text" id="element" my_value="100" />
I managed to fix it the issues, setting the value for each input was achieved by this line:
// Insert result after the current input field.
$(this).after(result);
and getting submit achieved by this line
sum += +$(this).text();
//console.log("Value sum "+sum);
$('#GrandTotal').val(sum);
As I show all result on span I used this below to hide
$( "span" ).hide();
working version on jsfiddle.net
https://jsfiddle.net/erkindunya/L3d4j8hv/17/
This might help one else who doing this
Related
I have a form that has a mobile field. On submit button I put an event to add a value to the mobile field (it adds the country region code automatically which is a fixed value of "11"), so when the user clicks on Submit, the JS adds the "11" value to the mobile so the this field goes to the data base like this "1155555555" (the user just typed "55555555").
Ok, the problem is that if the user left an empty field (all fields are required), and clicks on Submit, the form won´t be sent but it will add the value "11" to the mobile field no matter what, and when the user fills up the empty field and click on Submit for the second time, it will add AGAIN the value "11", so the mobile goes like "111155555555", and so on and so forth.
Basically, what I need is to prevent this function from happening multiple times. It has to happen only once. How do I achieve this using JS?
HTML:
<input id="mobile" name="MOBILE" type="tel"><input type="number" value="11" id="front" class="hide">
<button type="submit" onclick="append11()">SUBMIT</button>
JS:
function append11(){
var mobilenumber = document.getElementById("mobile");
var front = document.getElementById("front").value;
mobilenumber.value=front+mobilenumber.value;
alert(mobilevalue.value);
}
Why you don't append the 11 in the function?
Like:
function append11(){
var mobilenumber = document.getElementById("mobile");
mobilenumber.value="11"+mobilenumber.value;
alert(mobilevalue.value);
}
I think you should heed the comment responses to your original question. Your approach has some risks.
But I'll assume you're a beginner who's just trying to learn how to do something like what you're asking about, so the javascript below applies a few principles you might consider.
function isNumberValid9(num) {
console.log(num, num.length);
//check string length and pattern
//this could be combined into a single regex, e.g.: mobileValue.match("^[0-9]{9}$")
var isValid9 = num.length === 9 && num.match("^[0-9]+$");
console.log(isValid9); //display the value about to be returned
return isValid9;
}
/* Conditionally prepend "11" */
function maybeAppend11() {
var mobilenumber = document.getElementById("mobile");
var mobileValue = mobilenumber.value;
//only prepend "11" if the number matches your expected pattern and length
if (isNumberValid9(mobileValue)) {
var front = document.getElementById("front").value;
mobilenumber.value = front + mobileValue;
}
alert(mobilenumber.value);
}
<input id="mobile" name="MOBILE" type="tel" value="555555555"><input type="number" value="11" id="front" class="hide">
<button type="submit" onclick="maybeAppend11()">SUBMIT</button>
I am trying to create this JavaScript calculation with radio buttons. So If the user Checks the "delivered to home address" then the value of £5.99 will be added into the total box, but if the user selects the other radio button, then no price will get shown. I am pretty new to JavaScript so I may have a few errors, but i'd be grateful if you could help me out
<section id="collection">
<h2>Collection method</h2>
<p>Please select whether you want your chosen event ticket(s) to be delivered to your home address (a charge applies for this) or whether you want to collect them yourself.</p>
<p>
Home address - £5.99 <input type="radio" name="deliveryType" value="home" data-price="5.99" checked> |
Collect from ticket office - no charge <input type="radio" name="deliveryType" value="ticketOffice" data-price="0">
</p>
</section>
Total <input type="text" name="total" size="10" readonly>
JavaScript
let totalPrice = 0;
var RadioBtn = document.getElementById ('input[name=deliveryType]');
radioBtn.addEventListener("click", function() {
if(radioBtn.clicked) {
totalPrice += parseFloat(radioBtn.dataset.price)
total.value = " + totalPrice;
}
}
Here are my observations from the code provided:
The radioBtn variable was declared with Pascal Case (first letter
upper case) so it won't be referenced in the code since the other
lines use camelCase(starts with Lower case). change to camelCase and
stick with it through out the code.
Your selector - getElementById is used for Ids and it would return one
element, since you are passing a query selector
'input[name=deliveryType]' instead the code will not find the
element you are looking for
Since you are looking to add click events to the radio buttons, you can
use getElementsByName and provide the name of the radio
buttons. Then iterate through the resulting elements to apply the
click event... that way the click will be called for both radio
buttons.
No need to check if clicked inside the click event, you already know it
will be called when clicked only, instead you can add the
event parameter to get the click target and its information to apply
it as needed.
Example:
let totalPrice = 0;
let radioBtns = document.getElementsByName('deliveryType');
let totalEl = document.getElementsByName ('total')[0];
radioBtns.forEach(function(element, index){
element.addEventListener("click", function(event){
totalPrice += parseFloat(event.target.dataset.price); //remove += if the price should be the same everytime, replace with = or it will add the number to the total when clicked
totalEl.value = totalPrice + " totalPrice";
});
});
https://jsfiddle.net/dn4x7oy9/8/
I have two input fields and a variable:
var x = 5;
First: <input type="text" name="first">
Second: <input type="text" name="second">
When I input a value in the first input field I want to update and display the second input field value with: first-input-field-value * x
When I input a value in the second input field I want to update and display the first input field value with: x / second-input-field-value
A simple solution would be to implement event handlers that perform the respective arithmetic for each input element. Some things to consider would be:
ensuring the user supplied input is a valid number. Below I parse the current string value of the updated input and ensure the parsed result is a valid number before performing the arthimetic
use the input event ensure that arthimetic and input updates are peformed immediatly, and for different user interactions (keypress, paste from keyboard, etc)
In code this can be written as:
/* Query document for first and second input elements */
const inputFirst = document.querySelector('input[name="first"]');
const inputSecond = document.querySelector('input[name="second"]');
const x = 5;
/*
Add event handler for the input event that will be run when user interaction
with input causes value change
*/
inputFirst.addEventListener("input", (event) => {
/* Obtain current numeric value for this input after user interaction */
const value = Number.parseFloat(event.target.value);
if(!Number.isNaN(value)) {
/*
The value is a number, so we're safe to use it for arithmetic. Here
we update the value of the secondInput from the input event of the
firstInput
*/
inputSecond.value = value * x;
}
});
inputSecond.addEventListener("input", (event) => {
const value = Number.parseFloat(event.target.value);
if(!Number.isNaN(value)) {
inputFirst.value = value / x;
}
});
First: <input type="text" name="first">
Second: <input type="text" name="second">
I am using a form to build a block of text, the final output of which needs to be kept under a certain character count.
For the user, I need to be able to provide real-time character counting so they can adjust their entries as appropriate.
Basic HTML would be as follows:
<form>
<input type="text" id="#input1">
<input type="text" id="#input2">
</form>
<div class="character-counter">0</div>
However my JS/jQuery is not working very well: while it is outputting a counter in real time, it seems to be concatenating the final results in the output despite me parsing the variables as integers.
$('#input1').keyup(function() {
// Variables
var currentCharCount = parseInt($('.character-counter').text());
var fieldLength = parseInt($(this).val().length, 10);
var newCharCount = fieldLength + currentCharCount;
// Counter output
$('.character-counter').text(Number(newCharCount));
});
$('#input2').keyup(function() {
// Variables
var currentCharCount = parseInt($('.character-counter').text());
var fieldLength = parseInt($(this).val().length, 10);
var newCharCount = fieldLength + currentCharCount;
// Counter output
$('.character-counter').text(Number(newCharCount));
});
The correct solution will update the '.character-counter' div with the correct total character count between the fields every time a character is typed or deleted or pasted in.
Thanks!
You don't want the old value of the character-counter element at all, you purely want to use the lengths of the text in the two inputs. Separately: Don't use keyup, use input. (What if the user right-clicks and pastes? No keyup occurs...)
Separately, the id attributes of your input fields are incorrect: They shouldn't have the # on them.
So (see comments):
// You can hook the event on both fields with the same call
// Note using `input`, not `keyup`
$("#input1, #input2").on("input", function() {
// Get the length of each input's current value, then put it
// in the .character-counter div
$('.character-counter').text($("#input1").val().length + $("#input2").val().length);
});
<form>
<input type="text" id="input1">
<!-- No # here --------^ -->
<input type="text" id="input2">
<!-- Nor here ---------^ -->
</form>
<div class="character-counter">0</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
i have a small javascript form
<div id="calculator-text"><h2>Tape calculator - based on cable size 1 mm to 28 mm, with 15% overlap</h2></div>
<form name="form1" method="post" action="">
<div id="calcformlabel"><label for="val2">Enter your cable size</label> (in mm)</div>
<div id="calcformtext1"><input type="text" name="val2" id="val2"></div>
<div id="calcformbutton"><input type="button" name="calculate" id="calculate" value="Calculate"></div>
<div id="calcformresult">The tape size you require is:- <span id="result1" class="maintext1"></span> (mm)</div>
</form>
<script type="text/javascript">
var btn = document.getElementById('calculate');
btn.onclick = function() {
// get the input values
var val2 = parseInt(document.getElementById('val2').value);
// get the elements to hold the results
var result1 = document.getElementById('result1');
// create an empty array to hold error messages
var msg = [];
// check each input value, and add an error message
// to the array if it's not a number
if (isNaN(val2)) {
msg.push('<span class="maintext1">Enter your cable size</span>');
}
// if the array contains any values, display the error message(s)
// as a comma-separated string in the first <span> element
if (msg.length > 0) {
result1.innerHTML = msg.join(', ');
} else {
// otherwise display the results in the <span> elements
result1.innerHTML = val2 * 3.142 * 1.15;
}
};
</script>
basically this is a simple calculation
a) how can i get this to output to 2 decimal places (and obviously round up or down depending on -.5 = round down and +.5 = round up)
b) replace the input type button for an image ( i have tried the obvious code and >input type = image>, basically these do actually work but instead of displaying the actual result, they display the result in a split second then reload the page with the blank form again...
any help on this would be much appreaciated
thanks in advance
for a part of your question
you can round javascript to specific precision by
Link :Number rounding in JavaScript
var original=28.453
1) //round "original" to two decimals
var result=Math.round(original*100)/100 //returns 28.45
2) // round "original" to 1 decimal
var result=Math.round(original*10)/10 //returns 28.5
3) //round 8.111111 to 3 decimals
var result=Math.round(8.111111*1000)/1000 //returns 8.111
The .toFixed() method lets you round off to n decimal places, so:
result1.innerHTML = (val2 * 3.142 * 1.15).toFixed(2);
I think the problem you're having with the image is that <input type="image"> defines the image as a submit button. Perhaps just include a standard image with an <img> tag rather than <input type="image">. If you give it an id='calculate' it should still work with your existing JS.
Or you could use a button element containing an img element so that you can specify the type (as not being submit):
<button type="button" id="calculate"><img src="yourimage"></button>
(I'm not sure that you need a form at all for this functionality since you don't seem to want to submit anything back to the server.)
To swap the button for an image, replace the button <input> with this code:
<img src="http://www.raiseakitten.com/wp-content/uploads/2012/03/kitten.jpg" name="calculate" id="calculate" value="Calculate" onclick="document.forms['form1'].submit();" />
It adds the image and a submit function for your form.
To round to two decimal places, use this function:
function twoDP(x){
return Math.round(x*100)/100
}
use it like this:
twoDP(100/3) //returns 33.33
it might also be relevant for you to use Math.PI
var result = val2 * Math.PI * 1.15 ;