Perform calculation of innerHTML number input - javascript

At the moment, I display the amount of characters which are typed into a text box.
I wish to use an alternative display option and show the estimated duration. This means the inputted character amount needs dividing by 15 to give an estimated time (there is roughly 15 characters to 1 second of speech)
How can I add a math calculation to the function below?
var inputElement = document.getElementById('inputTXT');
inputElement.addEventListener('keyup', function(e) {
boxInput = e.target.value;
document.getElementById('number').innerHTML = boxInput.length;
});

You can add an extra element and use that element to calculate the result of dividing the number of characters from the input with the length method and then dividing by 15. Note I use Math.round() to round the numbers.
var inputElement = document.getElementById('inputTXT');
inputElement.addEventListener('keyup', function(e) {
boxInput = e.target.value;
document.getElementById('number').innerHTML = boxInput.length;
document.getElementById('duration').innerHTML = Math.round(boxInput.length/15);
});
<form>
<input type="text" id="inputTXT" name="firstname">
<div>
<label>characters: <label id="number">0</label></label>
</div>
<div>
<label>duration: <label id="duration">0</label></label>
</div>
</form>

Related

Input field allows 6 characters when there is 5 max allowed

I have a function that removes numbers from string, it also should allow for max 5 letters to be entered. When I enter 5, and then another letter or number I can see it in console log, how can I avoid this?
document.getElementById("test").addEventListener("input", (e) => {
console.log(e.target.value);
let temp = e.target.value.replace(/[0-9]/g, '');
e.target.value = temp.substr(0, 5);
})
<input id="test" type="text">
You are loggging the value before removing the excess chars. Just move your console.log to the end of the function.
document.getElementById("test").addEventListener("input", (e) => {
let temp = e.target.value.replace(/[0-9]/g, '');
e.target.value = temp.substr(0, 5);
console.log(e.target.value);
})
<input id="test" type="text">
The problem with your code is that you are reading it from the current target that allows any number of characters, and later you are setting the substring from 0 to 5 on its value.
The simple fix would be to ask HTML to limit the number of characters so that the 6th character is never allowed.
This can be achieved by maxlength property.
<input id="test" type="text" maxlength="5">

Adding a score to every input field the user fills in the form and displaying it

Currently i have developed a program that gets the count of all the inputs field and adding up a percentage for the numbers of fields that are filled individually.
what i need now here, i need to assign a number to each input field and when the user fills an input field i need to show it to the user as a " SCORE ".
below is the program i have built.
<html>
<body>
<label> Name </label>
<input class="track"/>
<label> Name </label>
<input class="track"/>
<h5>Profile Strength <span class='perc'>0</span>%</h5>
</body>
</html>
and the JavaScript is
<script>
$('.track').change(function(e) {
update_progress();
});
// supports any number of inputs and calculates done as %
function update_progress() {
var count = $('.track').length;
var length = $('.track').filter(function() {
return this.value;
}).length;
var done = Math.floor(length * (100 / count));
$('.perc').text(done);
$('.meter').width(done + "%");
}
so when you fill the first input field the 'Profile strength' will show 50% as there are only 2 input fields, and when you fill the second input it will show 100%.
i want to show a number instead of a percentage here like
input 1 = 10
input 2 = 20
so when the user fills input 1 his "SCORE" will be 10,
and when the user fills the next input the total must add on and show 30 in real time.
sorry if have confused a few developers but this the only way i understood the assignment i got.
Try the following:
Html:
<html>
<body>
<label> Name </label>
<input class="track" data-score=10 />
<label> Name </label>
<input class="track" data-score=20 />
<h5>Profile Strength <span class='perc'>0</span>%</h5>
<h5>Score <span id="score">0</span></h5>
</body>
</html>
JS:
$('.track').change(function(e) {
update_progress();
});
// supports any number of inputs and calculates done as %
function update_progress() {
var score = 0
$('input.track').each(function(){
var _score = $(this).data("score")
if ($(this).val().length > 0) {
score += _score
}
})
$('#score').text(score)
var count = $('.track').length;
var length = $('.track').filter(function() {
return this.value;
}).length;
var done = Math.floor(length * (100 / count));
$('.perc').text(done);
$('.meter').width(done + "%");
}
Or, a live version https://jsfiddle.net/wmt6cznh/2/
Is this what you want to achieve?

How to find the number of positive and negative numbers are there on an input field?

My question is there are 3 input text field and a button, whatever the user enters and press the button, an alert should say how many negative numbers and how many positive numbers are on the text field?
Here is a working example The code is explained as below.
If you want to enter a number in each of the text field and click the button which tells the number of positive and negative numbered entered then here is your code,
You HTML code,
<input id="one" type="text"/>
<input id="two" type="text"/>
<input id="three" type="text"/>
<input type="button" onclick="check();" value="check">
Now you can write the script as follows,
function check(){
//Converting the values to integer
var x = parseInt(document.getElementById("one").value);
var y = parseInt(document.getElementById("two").value);
var z = parseInt(document.getElementById("three").value);
//Initializing the positive and negative count to 0
var posCount = 0;
var negCount = 0;
//Incrementing postive and negative count depending whether it is positive or negative
if(x>=0){
posCount++;
}else{
negCount++;
}
if(y>=0){
posCount++;
}else{
negCount++;
}
if(z>=0){
posCount++;
}else{
negCount++;
}
alert("Positive numbers: "+posCount);
alert("Negative numbers: "+negCount);
}

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.

Decrease variable by 1 Javascript

<input type='text' maxlength='32' onkeypress='previewLength(32)'>
I want to decrease 32 with 1 each time a key is pressed
Im using this for a length preview (max length is 32 and each time a key is pressed it gets decreased by 1 and shows the user how much he has left)
<script>
function previewLength (maxLength) {
maxLength = maxLength -= 1;
document.getElementById('CounterLength').innerHTML = maxLength;
}
</script>
Use the length of the actual value instead of counting keypresses (as for example the backspace key would reduce the length instead of increasing it):
<input type="text" maxlength="32" onkeypress="previewLength(this.maxLength, this.value.length, 'CounterLength');">
<script type="text/javascript">
function previewLength (maxLength, actualLength, id) {
document.getElementById(id).innerHTML = maxLength - actualLength;
}
</script>
(By also sending the maxlength and display element id into the function, it can be reused for multiple elements.)
You have some misconceptions, you'll want to look at the actual value, not the number of keypresses. For example: backspace, and arrow-left are also keypresses but they don't increase the length of the value.
html:
<input type='text' maxlength='32' onkeypress='previewLength(this, 32)'>
^- use `this`
js:
function previewLength (input_element, maxLength) {
var remain = maxLength - input_element.value.length;
document.getElementById('CounterLength').innerHTML = remain;
}
I would add some check not to show negative number, and just pass name of the control
window.updateCounter = function updateCounter(e, name) {
var len = e.value.length
, max = e.maxLength
, remaining = (max - len) > 0 ? max-len : 0
document.getElementById(name).innerHTML = remaining
}
markup
<input type='text' maxlength='32' onkeypress='updateCounter(this, "counter")'/>
<span id='counter'>32</span>

Categories