It seems onChange="myFunction()" is only calling my function once? - javascript

I have the following HTML that is within a form, to accept 2 numbers from two separate inputs
<input type="number" id="amount" name="amount" value="0" onchange="ltv()">
<input type="number" id="property_value" name="property_value" value="0" onchange="ltv()">
<p id="ltv"></p>
Then some JavaScript
function ltv() {
var amount = document.getElementById("amount").textContent;
var property_value = document.getElementById("property_value").textContent;
document.getElementById("ltv").innerHTML = Math.round(amount/property_value*100);
};
However after entering a number into the "amount" input the ltv element is updated with NaN which is to be expected at this stage as only the first variable in the math operation is set, however upon entering the second number and tabbing away from the input field the ltv is not updated again.

Seems like textContent isn't returning anything. Try to use .value
function ltv() {
var amount = document.getElementById("amount").value;
var property_value = document.getElementById("property_value").value;
document.getElementById("ltv").innerHTML = Math.round(amount/property_value*100);
};

Related

Converting form number field value structure

in a webpage, I asked users to input a field named "budget". I tried using the script below to create thousands separator for the entered number:
window.onload = function() {
document.getElementById("project-budget").onblur = function() {
this.value = parseFloat(this.value.replace(/,/g, ""))
.toFixed(0)
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
document.getElementById("display").value = this.value.replace(/,/g, "")
}
}
<input id="project-budget" step="5" required type="text" pattern="[0-9]*" class="test input-item text-field is_number numberVal" name="et_budget" min="1">
it changes the value perfectly but the problem is that making the field value as text cause cms to not understand value in this field. so I need to change the value back to simple numbers in a hidden field and use that hidden field to insert value to database.
how can I change the value back?
for example user enters 1000000 and the script changes it to 1,000,000. I want to print 1000000 in a hidden field.
This might help.
function parseBudget(element) {
const value = parseFloat(element.value.replace(/,/g, ''));
console.log(value);
element.value = value.toFixed(0)
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
document.querySelector("#forCms").value = value;
}
<input id="project-budget" step="5" required type="text" pattern="[0-9]*" onblur="parseBudget(this)" class="test input-item text-field is_number numberVal" name="et_budget" min="1">
<input type="number" id="forCms">

Javascript function adding checkboxes to a total number?

I have a function where I'm trying to add the total number of checkboxes ticked to a value that is already displayed in the textbox. The solution I have works but it doesn't update properly if I uncheck the boxes and click total again.
Is there a way I can fix this so that the textbox updates accordingly?
HTML
<td><input type="text" name="Yeses" id="NumberofRisks" class = "form-control" value ="<?php echo $row['Total-Score'];?> " style = "width:50px"></td>
Javascript
function sum()
{
sumField = document.getElementById("NumberofRisks");
var sum = sumField.value;
$("input[name^='yanswer']:checked").each(function(){
sum++;
});
sumField.value = sum;
}
You are updating the value of the input after every call to function sum().
Instead have the initial sum value.
Then every time use this value.
var initial = $("#NumberofRisks").val();
function sum()
{
$("#NumberofRisks").val(initial + $("input[name^='yanswer']:checked").length);
displayRating($("#NumberofRisks").val());
}
Keep the original value of the textbox in a variable. Add an event listener to the checkboxes that count the number of checked boxes and adds that number to the original value, then updates the textbox.
Something like this:
HTML:
<input type="checkbox" class="check" />
<input type="checkbox" class="check" />
<input type="checkbox" class="check" />
<input type="textbox" class="text" />
JS:
//Store the original value. The 5 here should be whatever was supposed to be in the textbox.
var originalValue = 5;
$('.text').val(originalValue);
$('.check').on('change', function() {
//Count the number of checked boxes and add it to the original value for display.
var checked = $('.check:checked').length;
$('.text').val(originalValue+checked);
});
Here's a fiddle.

.onblur function return as a variable.value?

http://jsfiddle.net/beY6d/
I want to make a simple HTML+JS page that basically gives the user 4 text fields to write the name of some product and an extra field that displays the remaining credit in the 5th text field.
<input type="text" value="0" class="product" id="shirtItems"/><br>
<input type="text" value="0" class="product" id="pantsItems"/><br>
<input type="text" value="0" class="product" id="hatItems"/><br>
<input type="text" value="0" class="product" id="accesoryItems"/><br>
<input type="text" value="100" id="credit" disabled/>
var shirt= document.getElementById("shirtItems");
var pants= document.getElementById("pantsItems");
var hat= document.getElementById("hatItems");
var accesory= document.getElementById("accesoryItems");
var remainingDosh = document.getElementById("credit");
remainingDosh.value = 100;
There must be a .onblur (or .onfocus) event to make the "credit" field display 100 minus the sum of every other item.
Also, the price of the item must change depending on the color/type of item. Something like:
shirt.onblur = function(){
if (shirt.value == "Blue") {remainingDosh.value = remainingDosh-25}
if (shirt.value == "Red") {remainingDosh.value = remainingDosh-20;}
};
If you do typeof remainingDosh.value, you'll see that it logs string. This means you'll have to convert the string to a number if you don't want to risk having NaN show up on your page.
Convert it with parseInt() like so:
var remainingDosh.value = parseInt(remainingDosh,10)-25;
The second parameter, 10 is the radix, which in this case is decimal (though it defaults to decimal if left out I believe).
And the issue in question, as pointed out, is you're trying to do math on the element remainingDosh instead of using it's value.
Oh, and protip: instead of shirt.value, you can use this.value since the event comes from said element.
you're using remainingDosh instead of remainingDosh.value when you do your subtraction.

javascript calculation field comparison algorithm

Good day,
I have 3 text fields for input.
TotalWeight
CustomUnitWeight
CustomsNumberOfUnit
There should be a validation to make sure TotalCustomWeight matches TotalWeight (neither higher nor lower).
I started playing around trying to construct a function for validating this no luck and looking for assistance
Scenario :
User input total weight of pkg at 30, then put number of custom unit at 2 and the weight at 10. On click the function calculate 2 * 10 = 20 and look at the total weight 30 and compare the total custom weight. In this case 20 does not equal to 30 therfore throw error message.
HTML
<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnitsUSA" id="CustomsNumberOfUnits" />
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onChange="ChkWeight();" />
JAVASCRIPT
$(function(ChkWeight){
$('#CustomsUnitWeight').click(function() {
var TotalWeight = document.getElementById('TotalWeight');
var CustomUnitWeight = document.getElementById('CustomsUnitWeight');
var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits');
var TotalCustomWeight = CustomUnitWeight * CustomsNumberOfUnit;
if (TotalWeight != TotalCustomWeight) {
error message "pkg weight does not match total custom weight"
}
});
});
Well everything else is fine in your code just needs to put .value to get value from your input fields and converting string (simple text) to Float type and then calculate and show alert like
<body>
<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnits" id="CustomsNumberOfUnits"/>
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onblur="CheckWeight()" />
//I have changed the event as onblur and calling CheckWeight() function defined in javascript below.
</body>
<script type="text/javascrit">
function CheckWeight()
{
var TotalWeight = document.getElementById('TotalWeight').value;
var CustomUnitWeight = document.getElementById('CustomsUnitWeight').value;
var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits').value;
//parsing text value to Float type for multipication
var TotalCustomWeight = parseFloat(CustomUnitWeight) * parseFloat(CustomsNumberOfUnit);
if (TotalWeight != TotalCustomWeight)
{
alert("pkg weight does not match total custom weight");
}
}
</script
and Off course you must need to validate for value to be number before calculation. This works perfect.

Calculate one variable based on changing input

I have the following function:
function updateInput(ish){
document.getElementById("BetAmount").value = ish;
}
I have the following HTML inputs:
<input class="defaultText" type="number" name="BetAmount" id="BetAmount" onchange="updateInput(this.value)">
<input type="number" name="PotentialGain" id="PotentialGain" />
When users enter in a bet amount number(BetAmount), I would like to instantly show a calculated PotentialGain, which, for example, can be found by multiplying a constant by the specified bet amount entered in by the user.
I'm not very familiar with JavaScript, so any help is greatly appreciated!
Your code is almost correct - you are showing the result in the BetAmount field so no change is visible.
Change your code to:
document.getElementById("PotentialGain").value = ish;
Here's a working demo. I changed the event to onkeyup as onchange only happens on blur - i.e. when a field loses focus.
Here is the final JQuery function that I used.
function changeBet(bet) {
var moneyline = <?php echo json_encode($win) ?>;
var gain = moneyline * bet;
document.getElementById("PotentialGain").value = gain;
}
Along with these inputs:
<input type="text" name="BetAmount[]" id="BetAmount" onkeyup="changeBet(this.value);" >
<input type="number" name="PotentialGain" id="PotentialGain" />

Categories