input only allow number 1-100 javascript - javascript

i want to make input percentage using javascript
<input type="text" class="form-control" id="amount" name="amount">
i made the js so when i input, it's adding %
var amount = document.getElementById('amount');
amount.addEventListener('input', function(e){
amount.value = amount.value.replace('%','') + '%';
})
but it still can input character, i want to only allow number 1-100, is it possible?
or maybe you have suggestion about what is better to input for percentage

HTML input type attribute allows number value so that it will only be able to accept number values.
And you can also pass a max attribute that will set a limit for entered number.
e.g.:
<input type="number" class="form-control" id="amount" name="amount" max="[YOUR_NUMBER]">
Edit:
You can still validate your input with a JS function.
<input type="text" class="form-control" id="amount" name="amount">
let amount = document.getElementById('amount');
amount.addEventListener('input', function(e){
amount.value = amount.value.replace('%','')
let tmpValue = +amount.value
amount.value = 0 <= tmpValue <= 100 ? tmpValue + '%' : "[VALUE IF NOT 1<AMOUNT<100]";
})

A little late. This is an interesting example. One could incorporate some more logic here. The example below only allows numbers between 0 and 100 and adds the % at the end. Once you have entered a number up to max one, you have to start again. a new logic would have to be built in here.
let amount = document.getElementById('amount');
amount.addEventListener('input', function(){
const n = amount.value.replace('%','');
if ( n >= 0 && n <= 100 ) {
amount.value = amount.value.replace('%','') + '%'
} else {
amount.value = n.slice(0, -1) + '%'
}
})
<input type="text" class="form-control" id="amount" name="amount">

Related

Jquery: How can I compute total average of each function based from the values in the input type = number?

I am new to Javascript/Jquery and I would like to compute the final rating based from the value in the text box for each function name [1st column of the table] (core function, support function, research services).
The formula based from example:
Final Rating Core Administrative Function = (4.6 + 4.3)/2 (because there are only 2 core functions average value is available) * 0.65
Final Rating Support Function = (4.3 + 4.3)/2 * 0.2275
Final Rating for Research Function = (4 + 4)/2 * 0.1225
The requirement is that everytime the A value column of each row changes the final rating change as well.
Here is the Jquery of on how I get the A value:
//GET THE AVERAGE PER ROW
$(".q-value, .e-value, .t-value").change(function(){
let currentRow = $(this).closest('tr');
let EValue = parseInt(currentRow.find('.e-value').val());
let QValue = parseInt(currentRow.find('.q-value').val());
let TValue = parseInt(currentRow.find('.t-value').val());
currentRow.find('.a-value').val((EValue + QValue + TValue ) / 3);
});
the .q-value, .e-value, .t-value, .a-value are all inside a class.
I add 3 input type for each final rating functions
<input type="number" class="form-control form-control-sm" id="core-total" name="total_core" readonly>
<input type="number" class="form-control form-control-sm" id="support-total" name="total_support" readonly>
<input type="number" class="form-control form-control-sm" id="research-total" name="total_research" readonly>
so the value for each function will be dump in there.
Please help me on this. Im stuck in a days.
With the help of my colleague, this is already resolved. I actually hardcoded an if statement in each input type for each functions (core, support etc..)
#if($row->function_name == 'Core Functions')
<input type="number" onchange="setFourNumberDecimal(this)" class="form-control form-control-sm a-value-core" name="A[]" style="width: 50px" readonly>
#elseif($row->function_name == 'Support Functions')
<input type="number" onchange="setFourNumberDecimal(this)" class="form-control form-control-sm a-value-support" name="A[]" style="width: 50px" readonly>
#endif
#if($row->function_name == 'Research and Extension Services')
<input type="number" onchange="setFourNumberDecimal(this)" class="form-control form-control-sm a-value-research" name="A[]" style="width: 50px" readonly>
#endif
After that. He created a JS function for computation.
//COMPUTE AVERAGE FOR EACH FUNCTION
function computeAvg() {
// For Core Functions
const corevalues = document.getElementsByClassName("a-value-core")
let avg = 0
let total = 0
let count = 0
for (let x = 0; x < corevalues.length; x++) {
if (corevalues[x].value !== "") {
count++
total = total + parseFloat(corevalues[x].value)
}
}
avg = (total / count) * 0.65
$('#core-total-average').val(isNaN(avg) ? "" : avg)
// For Support Functons
avg = 0
total = 0
count = 0
const supvalues = document.getElementsByClassName("a-value-support")
for (let x = 0; x < supvalues.length; x++) {
if (supvalues[x].value !== "") {
count++
total = total + parseFloat(supvalues[x].value)
}
}
avg = total / count * 0.2275
$('#support-total-average').val(isNaN(avg) ? "" : avg)
// For Research Services
avg = 0
total = 0
count = 0
const resvalues = document.getElementsByClassName("a-value-research")
for (let x = 0; x < resvalues.length; x++) {
if (resvalues[x].value !== "") {
count++
total = total + parseFloat(resvalues[x].value)
}
}
avg = total / count * 0.1225
$('#research-total-average').val(isNaN(avg) ? "" : avg)
}

How to increment or decrement the Value from defined OLD value

The Value is passed to C-(running-summary-total) from A OR B then that value should be passed to D-(wordcount) and increase or decrease, starting from that defined value, Let say the value is 150 then the increment or decrement should start from that 150.
enter image description here
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="form-control" type="number" id="wordcount" onchange="calTotal();" name="wordcount" value="" min="1"
max="100000000000">
<input class="form-control" type="number" id="quantity" onchange="calTotal();" name="quantity" value="" min=""
max="100000000000">
<input type="number" readonly="readonly" min="1n" name="total" id="running-summary-total" value="0.00">
JAVASCRIT
function calTotal() {
let wordcount = $("#wordcount").val(); //get wordcount value
let quantity = $("#quantity").val(); //get quantity value
if (wordcount) { //if wordcount has value
var wc = wordcount * 0.098;
$("#running-summary-total").val(wc);
}
if (quantity && quantity < 0) { //if quantity has value and its smaller then 0 (negative value)
let oldtotal = $("#running-summary-total").val(); //getting the old total value
let calc = Math.abs(quantity) * 2; //added Math.abs to turn negative number into positive, and mulitply by 2
let newtotal = oldtotal / calc; // here we divide the old total by the quatity times 2
$("#running-summary-total").val(newtotal);
}
if (quantity && quantity > 0) { //if quantity has value and its bigger then 0 (positive value)
let oldtotal = $("#running-summary-total").val(); //getting the old total value
let calc = quantity * 2; //here we multiply quantity by 2
let newtotal = oldtotal * calc; // here we multiply the old total by the quantity times 2
$("#running-summary-total").val(newtotal);
}
}
ISSUE
The issue or problem i am getting is that the value does not increase or decrease from the value, kindly help
Here you go. Working code you.
A little tricky scenarios just i finally got after reading your question multiple times. To archive what you want: Assign you A or B value to a var = oldValue on select and display in the running-summary-total.
Once you update your word count it will calculate the value from the running-summary-total and * 0.098 as you wanted.
Working Demo: https://jsfiddle.net/usmanmunir/8ersy4mk/22/
Run snippet below to see it working. Select A or B and do the rest as you want to!
let oldValue = 0
function getAorB(event) {
oldValue = event.value
$("#running-summary-total").val(oldValue);
}
function calTotal() {
let wordcount = $("#wordcount").val(); //get wordcount value
let quantity = $("#quantity").val(); //get quantity value
if (wordcount) { //if wordcount has value
var wc = wordcount * .098;
var total = parseInt(oldValue) + wc
$("#running-summary-total").val(total);
}
if (quantity && quantity < 0) { //if quantity has value and its smaller then 0 (negative value)
let calc = Math.abs(quantity) * 2; //added Math.abs to turn negative number into positive, and mulitply by 2
let newtotal = total / calc; // here we divide the old total by the quatity times 2
$("#running-summary-total").val(newtotal);
}
if (quantity && quantity > 0) { //if quantity has value and its bigger then 0 (positive value)
let calc = quantity * 2; //here we multiply quantity by 2
let newtotal = total * calc; // here we multiply the old total by the quantity times 2
$("#running-summary-total").val(newtotal);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" id="a" name="gender" value="100" onclick="getAorB(this)">
<label for="a">Select A</label><br>
<input type="radio" id="b" name="gender" value="150" onclick="getAorB(this)">
<label for="b">Select B</label><br>
<br> D <input class="form-control" type="number" id="wordcount" onchange="calTotal();" name="wordcount" value="" min="1" max="100000000000"> E <input class="form-control" type="number" id="quantity" onchange="calTotal();" name="quantity" value="" min=""
max="100000000000"> C <input type="number" readonly="readonly" min="1n" name="total" id="running-summary-total" value="0.00">

Javascript and JQuery issue with Wordpress

I'm working on a website and wanting to do advanced stuff (at least for me) that is way over my head. My javascript knowledge is extremely limited and need help with this.
I have an html form that accepts 5 text input fields labeled 1-5 representing a percentage distribution. I want to use javascript to do the following:
Read all fields and make sure the total sum is equal to 100.
Disable unnecessary fields when total sum equals 100.
Disable Submit button if total sum is not 100%.
Add the % at the end of the user entry.
I found two separate scripts to accomplish all this, one is javascript and the other one is JQuery. For some reason the JQuery is not working and it is yielding the following error:
Uncaught TypeError: $ is not a function
I've tried modifying the JQuery code, as suggested in multiple solutions online, like the following:
(function($){ "JQuery Code here" })(jQuery);
This get's rid of the error, however the JQuery code does not work.
Both the javascript.js and the JQuery.js files are being propperly enqueued in the WP theme's functions.php file.
Any help will be greately appreciated!!
HTML
<label for="entryFee">Entry Fee:</label>
<input id="entryFee" name="entry_fee" onblur="this.value = '$' + formatNumber(this.value, 1, 2, true)" type="text" value="" placeholder="$100.00" />
<h4>Prize Distribution</h4>
<label for="1stPlace">1st Place:</label> <input id="1stPlace" name="1st_place" type="text" onblur="this.value = formatNumber(this.value, 1, 0, true) + '%'" placeholder="60%" maxlength="3" size="4" class="percentageField" required />
<label for="2ndPlace">2nd Place:</label> <input id="2ndPlace" name="2nd_place" type="text" onblur="this.value = formatNumber(this.value, 1, 0, true) + '%'" placeholder="30%" maxlength="3" size="4" class="percentageField" />
<label for="3rdPlace">3rd Place:</label> <input id="3rdPlace" name="3rd_place" type="text" onblur="this.value = formatNumber(this.value, 1, 0, true) + '%'" placeholder="10%" maxlength="3" size="4" class="percentageField" />
<label for="4thPlace">4th Place:</label> <input id="4thPlace" name="4th_place" type="text" onblur="this.value = formatNumber(this.value, 1, 0, true) + '%'" placeholder="0%" maxlength="3" size="4" class="percentageField" />
<label for="5thPlace">5th Place:</label> <input id="5thPlace" name="5th_place" type="text" onblur="this.value = formatNumber(this.value, 1, 0, true) + '%'" placeholder="0%" maxlength="3" size="4" class="percentageField" />
<span id="percent">0</span>%
<input id="submitButton" type="submit" value="Submit" disabled>
</form>
Javascript
// Reformats a number by inserting commas and padding out the number of digits
// and decimal places.
//
// Parameters:
// number: The number to format. All non-numeric characters are
// stripped out first.
// digits: The minimum number of digits to the left of the decimal
// point. The extra places are padded with zeros.
// decimalPlaces: The number of places after the decimal point, or zero to
// omit the decimal point.
// withCommas: True to insert commas every 3 places, false to omit them.
function formatNumber(number, digits, decimalPlaces, withCommas)
{
number = number.toString();
var simpleNumber = '';
// Strips out the dollar sign and commas.
for (var i = 0; i < number.length; ++i)
{
if ("0123456789.".indexOf(number.charAt(i)) >= 0)
simpleNumber += number.charAt(i);
}
number = parseFloat(simpleNumber);
if (isNaN(number)) number = 0;
if (withCommas == null) withCommas = false;
if (digits == 0) digits = 1;
var integerPart = (decimalPlaces > 0 ? Math.floor(number) : Math.round(number));
var string = "";
for (var i = 0; i < digits || integerPart > 0; ++i)
{
// Insert a comma every three digits.
if (withCommas && string.match(/^\d\d\d/))
string = "," + string;
string = (integerPart % 10) + string;
integerPart = Math.floor(integerPart / 10);
}
if (decimalPlaces > 0)
{
number -= Math.floor(number);
number *= Math.pow(10, decimalPlaces);
string += "." + formatNumber(number, decimalPlaces, 0);
}
return string;
}
JQuery
(function($){
$('.percentageField').keyup( function () {
//limit the value to between 0 and 100
var thisVal = parseInt($(this).val(), 10);
if (!isNaN(thisVal)) {
thisVal = Math.max(0, Math.min(100, thisVal));
$(this).val(thisVal);
}
//get total of values
var total = 0;
$('.percentageField').each(function() {
var thisVal = parseInt($(this).val(), 10);
if (!isNaN(thisVal))
total += thisVal;
});
//change the value of the current entry to limit sum to 100
if (total > 100) {
$(this).val(thisVal - (total - 100));
total = 100;
}
if (total == 100) {
//enable submit button
$('#submit_button').removeAttr('disabled');
//disable empty input fields
$('.percentageField').each(function() {
var thisVal = parseInt($(this).val(), 10);
if (isNaN(parseInt($(this).val(), 10)) || thisVal == 0)
$(this).attr('disabled','disabled');
});
}
else {
//disable submit button
$('#submitButton').attr('disabled','disabled');
//enable all input fields
$('.percentageField').removeAttr('disabled');
}
//update percentage
$('#percent').html(total);
});
})(jQuery);
The JQuery script was running before the DOM was ready.
Enclosing the entire code set within $('document').ready(function() did the trick:
(function($){
$('document').ready(function()
{ <<JQuery Code>> });
})(jQuery);

javascript percentages issue

I am trying to calculate the following formula to return a numerical value from 0 - 100 (a grade) depending on the input from a user,
Grade = Exam Worth × Exam Score + (100% − Exam Worth) × Current Grade
and am using the following code to do so,
var total = ExamWorth * ExamScore + (100 - ExamWorth) * CurGrade;
Where my 3 variables are just being pulled in from html like so,
<input type="text" class="form-control" id="aimGrade">
However when I try and calculate I am always getting incorrect answers that I believe have to do not being sure how to convert this to a decimal.
For example an input of ExamWorth = 50 ExamScore = 80 and curGrade = 70 should return a value of 90. Where as i am getting a return of 7500 with the same input.
Perhaps you could make your inputs numbers:
<input type="number" class="form-control" id="aimGrade" min="0" max="100" />
which, as you can see, also allows you to do fancy things like add min and max values.
Then you will still have to use the javascript parseFloat() function:
var fExamWorth = parseFloat(ExamWorth);
Lastly, you may need to revisit your calculation. If your ExamWorth is a value out of 100 (i.e. a percentage), you will need to divide the final result by 100:
var total = (ExamWorth * ExamScore + (100 - ExamWorth) * CurGrade) / 100;
If it is really a decimal/proportion (i.e. a value between 0 and 1) then it should read:
var total = ExamWorth * ExamScore + (1 - ExamWorth) * CurGrade;
I'm guessing you are mixing up 100% and 100.
If ExamWorth is a value between 0 and 1, you should use 1 - ExamWorth instead of 100 - ExamWorth.
var total = ExamWorth * ExamScore + (1 - ExamWorth) * CurGrade;
If ExamWorth is a value between 0 and 100, then you need to divide by 100.
var total = (ExamWorth * ExamScore + (100 - ExamWorth) * CurGrade) / 100;
Using the example you gave, you'd get 75 (instead of 7500), which is the correct number for calculating the final grade.
Your issue isn't converting to a decimal (7500 isn't going to become 90 when you divide by 100). Your algorithm is just wrong.
See algorithm description in the comments.
Also (FYI), there are two things to remember when working with values coming from user-supplied data:
All values extracted from HTML will be strings.
The order of operations in your algorithm might cause string
concatenation instead of mathematical addition.
So, here's an example (click to expand the snippet):
var worth = document.getElementById("worth");
var score = document.getElementById("score");
var grade = document.getElementById("grade");
document.getElementById("calc").addEventListener("click", function(){
// There are a number (no pun intended) of ways to convert strings to numbers
var worthVal = parseInt(worth.value, 10); // explicit
var scoreVal = +score.value; // coercion
var gradeVal = Number(grade.value) // function
// Algorithm:
var examPer = (scoreVal / 100) * worthVal; // % of exam worth achieved
var gradeAvg = gradeVal + examPer / 2; // average of grades
// Order of operations: Parenthesis, Exponents, Multiplication, Division, Addition, Subtraction
// Because of the string, any operand on either side of it will normally be converted to a string
// If we were to try to do all the math at once, we have to be very careful about order of operations
console.log("Result 1: " + (gradeVal + ((scoreVal / 100) * worthVal) / 2));
// But, if we do the math in steps and just put the result with the message, it's much simpler
console.log("Result 2: " + gradeAvg);
});
<input type="text" class="form-control" id="worth" placeholder="exam worth" value="50">
<input type="text" class="form-control" id="score" placeholder="score" value="80">
<input type="text" class="form-control" id="grade" placeholder="grade" value="70">
<input type="button" value="Calculate" id="calc">
UPDATE:
After some thought on this, I don't think the calculation should return 90 as you say you expected. I think it should return 75. Here's why:
You are providing us with the Exam Worth and using that in your calculations, but the only reason you would need that is to get a score (in points), for example:
Exam is weighted at 50
You got 80 percent correct
.8 x 50 = 40 (You got a score of 40 and a percent of 80)
But, to get the overall grade, we don't care about the fact that you got a score of 40 on the exam. We only care about the fact that you got 80%, so the Exam Weight is irrelevant.
To get the correct overall grade, all we need to do is add the two grades (70 and 80) and divide by 2 (75).
So, in that case, the code would be:
var worth = document.getElementById("worth");
var score = document.getElementById("score");
var grade = document.getElementById("grade");
document.getElementById("calc").addEventListener("click", function(){
var scoreVal = +score.value;
var gradeVal = Number(grade.value)
// Algorithm:
var gradeAvg = (scoreVal + gradeVal) / 2; // average of grades
// But, if we do the math in steps and just put the result with the message, it's much simpler
console.log("Result 2: " + gradeAvg);
});
<input type="text" class="form-control" id="worth" placeholder="exam worth" value="50">
<input type="text" class="form-control" id="score" placeholder="score" value="80">
<input type="text" class="form-control" id="grade" placeholder="grade" value="70">
<input type="button" value="Calculate" id="calc">

HTML5 number input - display as percentage instead of decimal

I have a form including number inputs which are supposed to represent percentages, which are set up approximately like below:
<input type="number" min="0" max="1" step="0.01" />
Currently, the values show up as decimals, for example, 0.25. I think it'd be a lot more user-friendly if the number displayed in the text field showed up as a percentage instead. I've already disabled keyboard input on the field using the below jQuery code, so I'm not worried about users inputting rogue values:
$('input[type="number"]').keypress(function (field) {
field.preventDefault();
});
Is there an easy way to change the number fields to display a percentage?
Thank you!
There are two ways which I hope will work.
If you want percentages in input and need to convert it to decimals in js then:
<input type="number" min="1" max="100" id="myPercent"/>
in js:
document.getElementById('myForm').onsubmit = function() {
var valInDecimals = document.getElementById('myPercent').value / 100;
}
If scenario is reverse then:
<input type="number" min="0" max="1" step="0.01" id="myPercent"/>
in js:
document.getElementById('myForm').onsubmit = function() {
var valInDecimals = document.getElementById('myPercent').value * 100;
}
While not a HTML5 input type='number', the solution bellow uses input type='text' to the same effect. The rational of not using type='number' being humans require a nicely formatted string like "23.75%" while robots prefer to read integers and floating points should be avoided. The snippet bellow does just that to 2 decimal places.
I haven't tested it on a mobile, but I think the number pad should appear as with input type='number'.
Codepen.io: Commented code can be found here
document.querySelector('.percent').addEventListener('input', function(e) {
let int = e.target.value.slice(0, e.target.value.length - 1);
if (int.includes('%')) {
e.target.value = '%';
} else if (int.length >= 3 && int.length <= 4 && !int.includes('.')) {
e.target.value = int.slice(0, 2) + '.' + int.slice(2, 3) + '%';
e.target.setSelectionRange(4, 4);
} else if (int.length >= 5 & int.length <= 6) {
let whole = int.slice(0, 2);
let fraction = int.slice(3, 5);
e.target.value = whole + '.' + fraction + '%';
} else {
e.target.value = int + '%';
e.target.setSelectionRange(e.target.value.length - 1, e.target.value.length - 1);
}
console.log('For robots: ' + getInt(e.target.value));
});
function getInt(val) {
let v = parseFloat(val);
if (v % 1 === 0) {
return v;
} else {
let n = v.toString().split('.').join('');
return parseInt(n);
}
}
<input class="percent" type="text" value="23.75%" maxlength="6">
Maybe add a function, the outputted number (for example 0.25) * 100 + "%", on this way you always have it in percents.
function topercentage() {
var outputnumber = outputnumber * 100 + "%";
}
In this example outputnumber is the number for example 0.25. I hope this works.

Categories

Resources