Output wont show (javascript) - javascript

I have 1 input. And it has to print out 2 outputs 1 with -1 to the output and the other with -2. But the output doesn't show anything. can someone tell me what I'm doing wrong here.
Code:
// Meters en Centimeters value
function updateTotal() {
const list = document.getElementsByClassName("AutosubmitCalculator");
const values = [];
for (let i = 0; i < list.length; ++i) {
values.push(parseFloat(list[i].value));
}
let total = values.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
});
document.getElementById("schermentotaal").value = total - 2;
document.getElementById("schermentotaal2").value = total - 1;
}
HTML Input:
<div class="InputField InputMeters">
<input type="tel" name="iFenceMeters" id="FenceMeters" class="AutosubmitCalculator" data-minimum-length="1" tabindex="1" placeholder="00" maxlength="3" value="">
<div class="FormExclamation Tipped Hidden" id="FormCalculatorExclamationFence">0</div>
</div>
HTML Output:
<div class="SummaryRow">
<strong>Schermen</strong>
<input name="schermentotaal" type="text" id="schermentotaal" value=""></input>
</div>
<div class="SummaryRow">
<strong>Palen en onderplaten</strong>
<input name="schermentotaal2" type="text" id="schermentotaal2" value=""></input>
</div>
Thanks in advance :D

You're not calling your updateTotal anywhere. I suggest you run this function on the oninput event on your input field. This will make it so that whenever you enter a number it will run the function updateTotal.
You also have some additional errors, such as you are trying to get the element with the id total but don't have an element with this id in your HTML.
document.getElementById("total").value
I've changed this to be schermentotaal2 which is a valid id in your HTML:
document.getElementById("schermentotaal2").value
See working example below:
function updateTotal() {
const list = document.getElementsByClassName("AutosubmitCalculator");
const values = [];
for (let i = 0; i < list.length; i++) {
values.push(parseFloat(list[i].value));
}
let total = values.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
});
document.getElementById("schermentotaal").value = (total - 2) || '';
document.getElementById("schermentotaal2").value = (total - 1) || '';
}
<div class="InputField InputMeters">
<input type="tel" name="iFenceMeters" id="FenceMeters" class="AutosubmitCalculator" data-minimum-length="1" tabindex="1" placeholder="00" maxlength="3" value="" oninput="updateTotal()" />
<div class="FormExclamation Tipped Hidden" id="FormCalculatorExclamationFence">0</div>
</div>
<div class="SummaryRow">
<strong>Schermen</strong>
<input name="schermentotaal" type="text" id="schermentotaal" value="" />
</div>
<div class="SummaryRow">
<strong>Palen en onderplaten</strong>
<input name="schermentotaal2" type="text" id="schermentotaal2" value="" />
</div>
Also, if you only have one input you may want to reconsider using a class to get the input value for this as you don't require a loop to get the value from one input field.

Related

how to append and remove div based on textbox value

Here is my code i want to append data based on all three textbox if textbox value is 2 and textbox2's value is 3 and textbox3's value is 1 the The result will be 2 apple 3banans and 1 cherry and user can also remove items with textbox value
I have tried to make this code but it is removing all items could you please help me to solve this problem
$(".change_qty").change(function(){
var total = $(this).val();
var oldLength = $(".box > span").length;
var change = total - oldLength;
var data_text= $(this).data("text");
if (change > 0) {
for (i = 0; i < change; i++) {
$(".box").append(`<span >${data_text}<br /></span>`);
}
}
else {
change = Math.abs(change)
$( ".box > span" ).each(function( index ) {
$(this).remove();
if (index == (change -1)) {
return false;
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="form-control input-sm change_qty" type="number" data-text="apple">
<input class="form-control input-sm change_qty" type="number" data-text="bananas">
<input class="form-control input-sm change_qty" type="number" data-text="cherry">
<div class="box" ></div>
$(".box > span").length does not regard your different input types. It might be easier to clear everything and recreate the whole output on change. That way the entries also keep the order of input.
$(".change_qty").change(function(){
//REM: Remove all entries
$(".box").empty();
//REM: Recreate all entries
$(".change_qty").each(function(){
let tThis = $(this);
let tText = tThis.data('text');
let tQuantity = Math.abs(tThis.val());
//REM: Append quantity of entries to .box
for(let i=0, j=tQuantity; i<j; i++){
$(".box").append(`<span >${tText}<br /></span>`)
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="form-control input-sm change_qty" type="number" data-text="apple">
<input class="form-control input-sm change_qty" type="number" data-text="bananas">
<input class="form-control input-sm change_qty" type="number" data-text="cherry">
<div class="box" ></div>

How get the sum of all the checkbox values of checked items

let addonCheckboxes = document.querySelectorAll(".custom-checkbox")
let priceSection = document.getElementById("priceSection")
let customProductPricing = document.getElementById("customProductPricing")
for (let i = 0; i < addonCheckboxes.length; i++) {
addonCheckboxes[i].addEventListener("change", function() {
if (addonCheckboxes[i].checked != false) {
priceSection.textContent = parseInt(customProductPricing) + parseInt(addonCheckboxes[i].getAttribute("price"));
} else {
priceSection.textContent = parseInt(customProductPricing)
}
})
}
<input class="custom-checkbox" type="checkbox" price="150"></input>
<input class="custom-checkbox" type="checkbox" price="150"></input>
<input class="custom-checkbox" type="checkbox" price="150"></input>
<div id="priceSection">
</id>
<div id="customProductPricing">"150"</div>
I want to get the total of all the checkboxes if they are all checked. So far it gives only one value. And need to deduct the prices if the checkbox is unchecked.
This one has fixed all the errors you made in your markup, and simplified the code by alot.
const output = document.getElementById('priceSection');
const totalPrice = () => [...document.querySelectorAll('#prices input[type=checkbox]:checked')]
.reduce((acc, {
dataset: {
price
}
}) => acc + +price, 0);
document.getElementById('prices').addEventListener('change', () => output.textContent = totalPrice());
<div id="prices">
<input type="checkbox" data-price="10" />
<input type="checkbox" data-price="20" />
<input type="checkbox" data-price="30" />
</div>
<div id="priceSection"></div>
You are overwriting instead of summing. When you are iterating through an array of checkboxes and you find that more than one is checked your function fails.
You should firstly count the sum of checked checkboxes and then send it to priceSection, and when your sum is equal to zero you should set it parseInt(customProductPricing) like you did in else.
When the change event of the <input> elements is triggered, the update() method is called and the values in the page are collected and printed on the page. I don't understand the issue of lowering the price if the checkbox is not selected. Update the update() method to subtract unselected values from the total using the following approach; Add an else statement to the if block.
(function() {
let addonCheckboxes = document.querySelectorAll(".custom-checkbox");
function update()
{
let total = parseInt(document.getElementById("customProductPricing").textContent);
for(let i = 0 ; i < addonCheckboxes.length ; ++i)
if(addonCheckboxes[i].checked == true)
total += parseInt(addonCheckboxes[i].value);
document.getElementById("priceSection").innerHTML = "Result: " + total;
}
for(let i = 0 ; i < addonCheckboxes.length ; ++i)
addonCheckboxes[i].addEventListener("change", update);
})();
<input class="custom-checkbox" type="checkbox" value="10"/>
<label>10</label>
<input class="custom-checkbox" type="checkbox" value="20"/>
<label>20<label>
<input class="custom-checkbox" type="checkbox" value="30"/>
<label>30<label>
<!-- Static Value -->
<div id="customProductPricing">40</div>
<br><div id="priceSection" style="color: red;">Result: </div>
Using data set you can access price
let addonCheckboxes = document.querySelectorAll(".custom-checkbox")
let priceSection = document.getElementById("priceSection")
let customProductPricing = document.getElementById("customProductPricing")
let sum = 0
for (let i = 0; i < addonCheckboxes.length; i++) {
addonCheckboxes[i].addEventListener("change", function(e) {
console.log(e.target.dataset.price)
if (addonCheckboxes[i].checked != false) {
sum = sum +Number(e.target.dataset.price)
} else {
sum = sum -Number(e.target.dataset.price)
}
customProductPricing.innerHTML = sum
})
}
<input class="custom-checkbox" type="checkbox" data-price="150"></input>
<input class="custom-checkbox" type="checkbox" data-price="150"></input>
<input class="custom-checkbox" type="checkbox" data-price="150"></input>
<div id="priceSection">
</id>
<div id="customProductPricing">"150"</div>
As #Sercan has mentioned... I am also not sure about the issue of loweing the sum but I've whipped up something for you.
Hopefully it'll lead you to what you want to achieve.
let addonCheckboxes = document.querySelectorAll(".custom-checkbox")
let priceSection = document.getElementById("priceSection")
let customProductPricing = document.getElementById("customProductPricing");
var checkboxes = document.getElementsByClassName("custom-checkbox");
function sum(){
var total = 0;
for(let x = 0; x < checkboxes.length; x++){
let price = document.getElementsByClassName(x);
if(price[0].checked){
total = total + Number(price[0].dataset.price);
}
}
console.log('Sum = ' + total)
}
<input class="custom-checkbox 0" onclick="sum()" type="checkbox" data-price="150"></input>
<input class="custom-checkbox 1" onclick="sum()" type="checkbox" data-price="150"></input>
<input class="custom-checkbox 2" onclick="sum()" type="checkbox" data-price="150"></input>
<div id="priceSection"></id>
<div id="customProductPricing">"150"</div>

How will i show my data output inside an input element using Jquery

Here is my Javascript code:
$('#sb_add_ctrl').click(function() {
var value = $('#sel_control_num').val();
for (var i = 1; i <= 5; i++) {
value = value.replace(/(\d+)$/, function(match, n) {
const nextValue = ++match;
return ('0' + nextValue).slice(1);
});
$('#parent')[0].innerHTML += '<br>' + value;
}
})
Here is my HTML code:
<div><label> Control Number </label>
<input name="get_control_num" style="text-transform:uppercase"
class="form-control" id="sel_control_num" readonly>
</div>
<div class="form-group">
<label> Quantity </label>
<input class="form-control" name="quantity" type="number"
/>
<br>
<button type="button" id="sb_add_ctrl" class="btn btn-primary"> Add
Control Number </button>
</div>
<div class="form-group" id="parent"></div>
What I want to do is get the existing class of the input and show the data that is in innerHTML into an input element .I can't think of a proper solution cause I am still a beginner in javascript/jquery, I tried the other methods in jquery but still it doesn't work thanks for the help

How to get value from input element from this html using JavaScript and also changing the background of the input element

I need the javascript to change the background of input element to either red if the number greater than the preceding number or red if it is less than the preceding number
The value from the input element in html should be in array, then javascript should analyse the array and make the input element background green if the number is greater than the preceding number and then red if it less than the preceding number
The HTML
<form>
<input type="number" class="display" value="" id= "seat-1">
<input type="number" class="display" value="" id= "seat-2">
<input type="number" class="display" value="" id= "seat-3">
<input type="number" class="display" value="" id= "seat-4">
<input type="number" class="display" value="" id= "seat-5">
<input type="number" class="display" value="" id= "seat-6">
</form>
The Javascript to get the value
let seat1 = document.getElementById("seat-1").value;
let seat2 = document.getElementById("seat-2").value;
let seat3 = document.getElementById("seat-3").value;
let seat4 = document.getElementById("seat-4").value;
let seat5 = document.getElementById("seat-5").value;
let seat6 = document.getElementById("seat-6").value;
The Javascript to make it an array and print red or green at the input background
let seatRow1 = [ seat1, seat2, seat3, seat4, seat5, seat6];
for (let i = 0; i < seatRow1.length; i++) {
if ( (seatRow1[i + 1]) > seatRow1[i]) {
document.getElementByClassName("display").style.backgroundColor =
"green";
}
else {
document.getElementByClassName("display").style.backgroundColor =
"red";
}
}
Thanks
Rather than getting the element values on page load, you will need to check the values whenever one of them changes (since the values at page load will likely change as the user inputs information). One way to do that would be to listen on the input event and then check the value of the changed input and compare it to its siblings. For example:
const changeBackground = (elem, v1, v2) => {
if (v1 < v2) {
elem.style.backgroundColor = 'red';
} else if (v1 > v2) {
elem.style.backgroundColor = 'green';
} else {
elem.style.backgroundColor = 'transparent';
}
};
const inputs = document.querySelectorAll('input');
for (let input of inputs) {
input.addEventListener('input', (event) => {
const target = event.currentTarget;
const value = parseFloat(target.value);
const prev = target.previousElementSibling;
const next = target.nextElementSibling;
if (prev) {
changeBackground(target, value, parseFloat(prev.value));
}
if (next) {
changeBackground(next, parseFloat(next.value), value);
}
});
}
<form>
<input type="number" value="">
<input type="number" value="">
<input type="number" value="">
<input type="number" value="">
<input type="number" value="">
<input type="number" value="">
</form>

jQuery add ID increment to .html() appending on input onchange and refresh onchange value

I apologize for the wordy title but I haven't found a solution to my problem yet. I am a newbie with jQuery and web development so any guidance would be appreciated.
I have a <input> that allows user to enter a value (number) of how many rows of a set of input fields they want populated. Here's my example:
<div id="form">
<input id="num" name="num" type="text" />
</div>
<p> </p>
<div id="form2">
<form action="" method="post" class="form_main">
<div class="data">
<div class="item">
<input id="name" name="name[]" type="text" placeholder="name" /><br/>
<input id="age" name="age[]" type="text" placeholder="age" /><br/>
<input id="city" name="city[]" type="text" placeholder="city" /><br/>
<hr />
</div>
</div>
<button type="submit" name="submit">Submit</button>
</form>
My jQuery:
<script>
var itemNum = 1;
$("#num").on("change", function() {
var count = this.value;
var item = $(".item").parent().html();
//item.attr('id', 'item' + itemNum);
for(var i = 2; i <= count; i++) {
itemNum++;
$(".data").append(item);
}
})
</script>
I'm having problems adding an ID item+itemNum increment to <div class="item">... item.attr() didn't work. It doesn't append once I added that line of code.
Also, how can I get it so that once a user enters a number that populates rows of input fields, that if they change that number it will populate that exact number instead of adding to the already populated rows? Sorry if this doesn't make any sense. Please help!
Here is a DEMO
var itemNum = 1;
$("#num").on("change", function() {
$('.data div').slice(1).remove(); //code for removing previously populated elements.
var count = this.value;
console.log(count);
var item;
//item.attr('id', 'item' + itemNum);
var i;
for(i = 1; i <= count; i++) {
console.log(i);
item = $("#item0").clone().attr('id','item'+itemNum);
//prevent duplicated ID's
item.children('input[name="name[]"]').attr('id','name'+itemNum);
item.children('input[name="age[]"]').attr('id','age'+itemNum);
item.children('input[name="city[]"]').attr('id','city'+itemNum);
itemNum++;
$(".data").append(item);
}
})
Use clone() instead of html()
Try
var itemNum = 1,
item = $(".data .item").parent().html();;
$("#num").on("change", function () {
var count = +this.value;
if (itemNum < count) {
while (itemNum < count) {
itemNum++;
$(item).attr('id', 'item' + itemNum).appendTo('.data')
}
} else {
itemNum = count < 1 ? 1 : count;
$('.data .item').slice(itemNum).remove();
}
})
Demo: Fiddle

Categories