make the input value change without clicking button - javascript

I'm trying to make it give me the value that I put in at "summe:" when changing the numbers without actually clicking the calc button how do I do that? I tried with onchange but I cant figure out how to do it
const btncalc = document.querySelector('.calcit');
const summetext = document.querySelector('.summe');
const backend = document.querySelector('.backenduser');
backend.addEventListener('onchange', function() {
var backendanzahl = document.getElementsByClassName("backenduser")[0].value;
var appanzahl = document.getElementsByClassName("appuser")[0].value;
var mytext = "Anzahl der Summe:" + (+backendanzahl * 35 + +appanzahl * 7.5);
summetext.textContent = mytext;
});
App-Benutzer: <input type="number" placeholder="1-100" min="0" max="100" oninput="this.value = this.value > 100 ? 100 : Math.abs(this.value)" class='appuser'></input><br> Backendbenutzer: <input type="number" placeholder="1-15" min="1" max="15" oninput="this.value = this.value > 15 ? 15 : Math.abs(this.value)"
class='backenduser'></input><br>
<button class='calcit'>Berechnen</button><br>
<span class='summe'>0.00</span><br>

Use querySelectorAll to get references to both fields. And then forEach to apply event listener to both. Also as any points out the event you are looking for is change.
const btncalc = document.querySelector('.calcit');
const summetext = document.querySelector('.summe');
const backend = document.querySelector('.backenduser');
const updateOnChange = document.querySelectorAll('.update-on-change');
updateOnChange.forEach(input => {
input.addEventListener('change', function() {
var backendanzahl = document.getElementsByClassName("backenduser")[0].value;
var appanzahl = document.getElementsByClassName("appuser")[0].value;
var mytext = "Anzahl der Summe:" + (+backendanzahl * 35 + +appanzahl * 7.5);
summetext.textContent = mytext;
})
});
App-Benutzer: <input type="number" placeholder="1-100" min="0" max="100" oninput="this.value = this.value > 100 ? 100 : Math.abs(this.value)" class='appuser update-on-change'></input><br> Backendbenutzer: <input type="number" placeholder="1-15" min="1" max="15" oninput="this.value = this.value > 15 ? 15 : Math.abs(this.value)"
class='backenduser update-on-change'></input><br>
<button class='calcit'>Berechnen</button><br>
<span class='summe'>0.00</span><br>

Add an input handler. Change event only triggers when the element has lost focus.
element.addEventListener('input', function (evt) {
//do your stuff here
});
From MDN

Related

Change Position of a <a> element with a <img> inside

I am running into a problem in my application where I am trying to use an range slider to determine the position of a link containing an image. Basically it grabs the value of the ranges and uses it to determine the position. However, that does not happen. Instead it does absolutely nothing. Any thoughts on why this might occur?
JS Code:
//Social Media
var rangeX = document.getElementById("rangeX");
var rangeY = document.getElementById("rangeY");
var socialChooser = document.getElementById("socialsChooser");
var inputInvite = document.getElementById("inputInvite");
var submitsocialMedia = document.getElementById("submitSocial");
var Discord = document.getElementById("discord");
var YouTube = document.getElementById("youtube");
submitsocialMedia.addEventListener("click", function () {
var socialContainer = document.getElementById("socialsContainer");
if ( socialChooser.value === "discord") {
const a = document.getElementById("discordJoin");
if (a.children.length === 0) {
const linkText = document.createElement("img");
linkText.id = "linkText";
console.log(linkText.id);
linkText.src = "/html/imgs/Discord-Logo-White.png";
a.style.marginLeft = rangeX.value + "px";
a.style.marginTop = rangeY.value + "px";
a.appendChild(linkText);
a.title = "Discord Invite Link";
a.href = `${inputInvite.value}`;
}
}
HTML Code:
<input type="range" min="1" max="1000" value="500" id="rangeX"> X
<input type="range" min="1" max="1000" value="500" id="rangeY"> Y
It's hard to test your code. So many elements referenced but not available. Instead, here's a mockup of a working range slider/element added to DOM combo. Maybe it will help you discover what's not working in your setup.
let div = document.querySelector('div');
let rangeX = document.getElementById("rangeX");
let rangeY = document.getElementById("rangeY");
document.querySelector('button').addEventListener('click', () => {
div.innerHTML += `<a href='#' style='margin-left:${rangeX.value}px; margin-top:${rangeY.value}px;'>The link</a>`;
});
div a {
display: block
}
<input type="range" min="1" max="500" value="10" id="rangeX"> X
<input type="range" min="1" max="500" value="10" id="rangeY"> Y
<button>create</button>
<div>
</div>

How to save values chosen on slider to csv using JavaScript?

The final div of my code contains 5 sliders (I show here just 2) and a “finish” button. On click, I want to be able to:
Download a CSV file with the chosen values
Display the next div (without displaying the values)
I can only use JS and HTML.
/// phase C ////
var slider1 = document.getElementById("q1");
var demo1 = document.getElementById("demo1");
var vq1 = slider1.value;
demo1.innerHTML = slider1.value;
slider1.oninput = function() {
demo1.innerHTML = this.value;
}
var slider2 = document.getElementById("q2");
var demo2 = document.getElementById("demo2");
var vq2 = slider2.value;
demo2.innerHTML = slider2.value;
slider2.oninput = function() {
demo2.innerHTML = this.value;
}
function Phase_E_action() {
document.getElementById("Phase_D").hidden = true;
document.getElementById("Phase_E").hidden = false;
var fileContent = vq1 + "," + vq2;
var bb = new Blob([fileContent], {
type: 'text/plain'
});
var a = document.createElement('a');
a.downoload = "Exp" + Date().toString().slice(4, 24) + ".csv";
a.href = window.URL.createObjectURL(bb);
a.click();
}
<div id="Phase_D">
<span class="v50_15"><h1>Please state your opinion on Bob</h1></span>
<div class="slidecontainer">
<span class="v50_16"><p>On a scale from 0 to 100, when 0 means mean and ten means nice, how would you rate Bob?</p>
<input type="range" min="1" max="100" value="50" class="slider" id="q1">
<p>Value: <span id="demo1"></span></p>
</span>
</div>
<div class="slidecontainer">
<span class="v50_17"><p>On a scale from 0 to 100, when 0 means bad and ten means good, how would you rate Bob?</p>
<input type="range" min="1" max="100" value="50" class="slider" id="q2">
<p>Value: <span id="demo2"></span></p>
</span>
</div>
</div>
you need to put variable vq1, vq2 inside callback of input event or call directly slider1.value inside Phase_E_action() function
and for download it need to append to the current page
var vq1, vq2;
var slider1 = document.getElementById("q1");
var demo1 = document.getElementById("demo1");
demo1.innerHTML = slider1.value;
slider1.oninput = function() {
// put the variable here
vq1 = demo1.innerHTML = this.value;
}
var slider2 = document.getElementById("q2");
var demo2 = document.getElementById("demo2");
demo2.innerHTML = slider2.value;
slider2.oninput = function() {
vq2 = demo2.innerHTML = this.value;
}
function Phase_E_action() {
var fileContent = vq1 + "," + vq2;
console.log(fileContent)
var bb = new Blob([fileContent], {
type: 'text/plain'
});
var a = document.createElement('a');
a.download = "Exp" + Date().toString().slice(4, 24) + ".csv";
a.href = window.URL.createObjectURL(bb);
a.innerHTML = 'fff'
document.body.appendChild(a)
a.click();
document.body.removeChild(a);
}
<div id="Phase_D">
<span class="v50_15">
<h1>Please state your opinion on Bob</h1>
</span>
<div class="slidecontainer">
<span class="v50_16">
<p>On a scale from 0 to 100, when 0 means mean and ten means nice, how would you rate Bob?</p>
<input type="range" min="1" max="100" value="50" class="slider" id="q1">
<p>Value: <span id="demo1"></span></p>
</span>
</div>
<div class="slidecontainer">
<span class="v50_17">
<p>On a scale from 0 to 100, when 0 means bad and ten means good, how would you rate Bob?</p>
<input type="range" min="1" max="100" value="50" class="slider" id="q2">
<p>Value: <span id="demo2"></span></p>
</span>
</div>
<button onclick="Phase_E_action()">
Download CSV
</button>
note: you can't use download function here because the iframe is sanboxed and allow-downloads flag is not set

adding the sum of two separate functions

(ETA: I'm working on this for a class and the teacher wants everything to be "oninput"...yes, it's annoying :p )
I'm working on a form where each function miltiplies a number and gives me a "subtotal" on input. I'd like to take the two "subtotal" answers from the two functions and add them togething into a "total" amount. I feel like this should be simple but nothing I've tried works.
Here's what I've got in the javascript that works to give me the two subtotals:
function myCalculator() {
var qty1 = document.getElementById('qty1').value;
document.getElementById('subTotalOne').innerHTML = '$ ' + qty1 * 19.99;
}
function myCalculatorTwo() {
var qty2 = document.getElementById('qty2').value;
document.getElementById('subTotalTwo').innerHTML = '$ ' + qty2 * 37.99;
}
Here's the important parts of the html:
<div class="qty">
<label for="qty">Qty</label><br>
<input type="number" id="qty1" placeholder="0" oninput="myCalculator()"/><br>
<input type="number" id="qty2" placeholder="0" oninput="myCalculatorTwo()"/><br>
</div>
<div class="price">
<label for="price">Price</label>
<p>$19.99</p>
<p>$37.99</p>
</div>
<div class="subtotal">
<label for="subTotal">Total</label><br>
<span class="subTotalOne" id="subTotalOne">$</span><br>
<span class="subTotalTwo" id="subTotalTwo">$</span><br>
</div>
<div class="total">
<label for="total">Order Total</label><br>
<span class="orderTotal" id="orderTotal" oninput="orderTotal()">$</span><br>
</div>
I'm trying to add the subTotalOne and subTotalTwo and have them output at orderTotal, essentially. :)
Thanks!
//Global variables (concidering ID is unique)
let subTotalOne, subTotalTwo, qty1, qty2, orderTotal;
const setup = () => {
subTotalOne = document.getElementById('subTotalOne');
subTotalTwo = document.getElementById('subTotalTwo');
qty1 = document.getElementById('qty1');
qty2 = document.getElementById('qty2');
orderTotal = document.getElementById('orderTotal');
myCalculator();
myCalculatorTwo();
};
const updateTotal = (target, value) => {
if(target == null || value == null || Number.isNaN(value)) return;
target.textContent = `$ ${value.toFixed(2)}`;
target.setAttribute('data-value', value.toFixed(2));
}
const getTotal = () => {
if(subTotalOne == null || subTotalTwo == null) return 0;
const [value1, value2] = [
Number.parseFloat((subTotalOne.dataset?.value ?? 0), 10),
Number.parseFloat((subTotalTwo.dataset?.value ?? 0), 10)
];
if(Number.isNaN(value1) || Number.isNaN(value2)) return;
else return value1 + value2;
};
const updateOrderTotal = () => updateTotal(orderTotal, getTotal());
const myCalculator = () => {
const value = Number.parseFloat(qty1.value || 0, 10) * 19.99;
updateTotal(subTotalOne, value);
updateOrderTotal();
}
const myCalculatorTwo = () => {
const value = Number.parseFloat(qty2.value || 0, 10) * 37.99;
updateTotal(subTotalTwo, value);
updateOrderTotal();
}
window.addEventListener('load', setup);
<div class="qty">
<label for="qty">Qty</label><br>
<input type="number" id="qty1" placeholder="0" oninput="myCalculator()" min="0"><br>
<input type="number" id="qty2" placeholder="0" oninput="myCalculatorTwo()" min="0"><br>
</div>
<div class="price">
<label for="price">Price</label>
<p data-value="19.99">$19.99</p>
<p data-value="37.99">$37.99</p>
</div>
<div class="subtotal">
<label for="subTotal">Total</label><br>
<span class="subTotalOne" id="subTotalOne">$</span><br>
<span class="subTotalTwo" id="subTotalTwo">$</span><br>
</div>
<div class="total">
<label for="total">Order Total</label><br>
<span class="orderTotal" id="orderTotal" oninput="orderTotal()">$</span><br>
</div>
Here's how you do it:
function orderTotal() {
const qty1 = document.getElementById('qty1').value;
const qty2 = document.getElementById('qty2').value;
const total = parseInt(qty1) + parseInt(qty2);
document.getElementById('orderTotal').innerHTML = '$ ' + total;
}
Remove the oninput="orderTotal()" in your span element and trigger the above function using a button click e.g. <button onClick="orderTotal()">Calculate Total</button> or maybe when either of your two inputs' value changes. Also consider using const and let instead of var.
https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/
Instead of querying the DOM in Ray's answer--as DOM queries should generally be avoided since they are slow W3 Wiki, you could also consider using a shared variable between the two functions.
Also, consider using something else in place of innerHTML, mostly because of efficiency why-is-element-innerhtml-bad-code.
var total1;
var total2;
function myCalculator() {
var qty1 = document.getElementById('qty1').value;
total1 = qty1 * 19.99
document.getElementById('subTotalOne').textContent = '$ ' + total1;
}
function myCalculatorTwo() {
var qty2 = document.getElementById('qty2').value;
total2 = qty2 * 37.99;
document.getElementById('subTotalTwo').textContent = '$ ' + total2;
}
function orderTotal() {
document.getElementById('orderTotal').innerHTML = '$ ' + (total1 + total2);
//parentheses because '$' isn't a number so the numbers total1 and total2 will be treated like strings and joined together
}

How do I link this slider value with this <p> tag?

Everything in this code functions how I want it to except I don't know how to make whatever number is on the slider be applied to the number variable. Any help you can give I would appreciate so much!
var range = document.querySelector('.inputRange');
var field = document.getElementById('num1');
range.addEventListener('input', function (e) {
field.value = e.target.value;
});
field.addEventListener('input', function (e) {
range.value = e.target.value;
});
var number = 2000;
document.getElementById("id").innerHTML = number.toLocaleString('en');
var number2 = number;
if (number2 >= 10000) {
number2 = Math.round(+number + 10);
}
else if (number2 >= 5000) {
number2 = Math.round(+number + 5);
}
else {
number2 = Math.round(+number + 1);
}
document.getElementById("id2").innerHTML = number2.toLocaleString('en');
<input class="inputRange" type="range" min="1000" max="50000" value="1000" step="1000" id="slider"/>
<input class="inputNumber" id="num1" min="0" max="100" type="number" value="1000" />
<p> <span id="id"></span></p>
<p>$<span id="id2"></span></p>
http://jsfiddle.net/rY3Tj/292/ This should help!
var range = document.querySelector('.inputRange');
var field = document.getElementById('num1');
var number2 = 2001;
var numberHtml = document.getElementById("id");
var number2Html = document.getElementById("id");
range.addEventListener('input', function (e) {
field.value = e.target.value;
SetNumberValues(field.value);
});
field.addEventListener('input', function (e) {
field.value = e.target.value;
SetNumberValues(field.value);
});
function SetNumberValues(fieldValue)
{
numberHtml.innerHTML = fieldValue.toLocaleString('en');
if (fieldValue >= 10000) {
number2 = Math.round(+fieldValue + 10);
}
else if (fieldValue >= 5000) {
number2 = Math.round(+fieldValue + 5);
}
else {
number2 = Math.round(+fieldValue + 1);
}
document.getElementById("id2").innerHTML = number2.toLocaleString('en');
}
<input class="inputRange" type="range" min="1000" max="50000" value="1000" step="1000" id="slider"/>
<input class="inputNumber" id="num1" min="1000" max="50000" step="1000" type="number" value="1000" />
<p> <span id="id">2000</span></p>
<p>$<span id="id2">2001</span></p>
Here is working code: http://jsfiddle.net/e0s8z4hm/
Basically in range.addEventListener you were not updating value in #id2.
Current :
range.addEventListener('input', function (e) {
field.value = e.target.value;
});
Do it :
range.addEventListener('input', function(e) {
field.value = e.target.value;
$('#id2').html(e.target.value); // add this line
});

Javascript Equation Result is not showing after click on increment/decrement button

Well, I've a javascript tools where I can calculate percentage(%) of a sum(e.g 10,000). It's working when I put value(e.g 10,000) and percentage(e.g 10%) but problem is, I just added a increment and decrement button so user don't have to write 10,000, 30,000 etc. They can use my increment and decrement button. Unfortunately after press on increment and decrement button the Result is not showing. If i put the number manually then It's working.
Live Tools:
http://propertyjungle.com.au/tools.php
Javascript Code:
<script>
function incrementValue()
{
var value = parseInt(document.getElementById('pvalue1').value, 10);
value = isNaN(value) ? 0 : value;
value +=10000
document.getElementById('pvalue1').value = value;
}
function decrementValue()
{
var value = parseInt(document.getElementById('pvalue1').value, 10);
value = isNaN(value) ? 0 : value;
value -=10000
document.getElementById('pvalue1').value = value;
}
function toggleIncrement()
{
var value = parseFloat(document.getElementById('pvalue2').value, 10);
value = isNaN(value) ? 0 : value;
value +=0.1
document.getElementById('pvalue2').value = value;
}
function toggleDecrement()
{
var value = parseFloat(document.getElementById('pvalue2').value, 10);
value = isNaN(value) ? 0 : value;
value -=0.1
document.getElementById('pvalue2').value = value;
}
jQuery(document).ready(function () {
$('#pvalue1').change(function () {
var agentfee = parseFloat($('#pvalue1').val(), 10) * parseFloat($('#pvalue2').val(), 10) / 100;
$('#pvalue3').val(agentfee);
var percentagereduce = parseFloat($('#pvalue2').val(), 10) - 0.1;
var newvalue = parseFloat($('#pvalue1').val(), 10) * percentagereduce / 100;
$('#pvalue4').val(newvalue);
var takevalue1 = parseFloat($('#pvalue3').val(), 10);
var takevalue2 = parseFloat($('#pvalue4').val(), 10);
var finalvalue = takevalue1 - takevalue2;
$('#pvalue5').val(finalvalue);
});
$('#pvalue2').change(function () {
var agentfee = parseFloat($('#pvalue1').val(), 10) * parseFloat($('#pvalue2').val(), 10) / 100;
$('#pvalue3').val(agentfee);
var percentagereduce = parseFloat($('#pvalue2').val(), 10) - 0.1;
var newvalue = parseFloat($('#pvalue1').val(), 10) * percentagereduce / 100;
$('#pvalue4').val(newvalue);
var takevalue1 = parseFloat($('#pvalue3').val(), 10);
var takevalue2 = parseFloat($('#pvalue4').val(), 10);
var finalvalue = takevalue1 - takevalue2;
$('#pvalue5').val(finalvalue);
});
});
</script>
Html code:
<table>
<tr>
<td>House Sale Price:</td>
<td>$<input name="pvalue1" onkeypress="validate(event)" value="" placeholder=" Enter Sale Price" style="width:140px;" type="number" value="<?=$pvalue1?>" id="pvalue1" size="20" class="required inputfield2" required ></td>
<td><input type="button" onClick="incrementValue()" value="+" /><input type="button" onClick="decrementValue()" value="-" /> </td>
</tr>
<tr>
<td>Rate quoted by agent:</td>
<td> <input name="pvalue2" onkeypress="validate(event)" value="0" placeholder=" Percentage" style="width:140px;" type="number" value="<?=$pvalue2?>" id="pvalue2" size="20" class="required inputfield2" required >%</td>
<td><input type="button" onClick="toggleIncrement()" value="+" /><input type="button" onClick="toggleDecrement" value="-" /></td>
</tr>
</table>
<h2>Results</h2>
<table>
<tr><td>Agent Fees:</td><td>$<input name="pvalue3" value="0" placeholder="" type="number" value="<?=$pvalue3?>" id="pvalue3" size="10" class="resultfield" ></td></tr>
<tr><td></td><td><div id='show-me' style='display:none'><input name="pvalue4" value="0" placeholder="" type="number" value="<?=$pvalue4?>" id="pvalue4" size="10" class="resultfield" ></div></td></tr>
<tr><td>Reducing the rate the agent is charging by 0.1% will save you: </td><td>$<input name="pvalue5" value="0" placeholder="" type="number" value="<?=$pvalue5?>" id="pvalue5" size="10" class="resultfield" ></td></tr>
</table>
This is happening because changing the value of a field does not trigger the change event: Why does the jquery change event not trigger when I set the value of a select using val()?
If you don't feel like refactoring all of your code, you could simply trigger the jQuery change event, which would then run the calculations:
function toggleIncrement(){
...
$("#pvalue1").trigger("change");
}
function toggleDecrement(){
...
$("#pvalue1").trigger("change");
}
...
Example.

Categories

Resources