I have a field that will round up to the nearest .25. This is working fine in Chrome but for some reason it will not allow me to type say 2.25 in IE or Firefox. It ignores that I am typing a dot. Is there something obvious I'm missing here?
Edit One thing I have noticed is that if I change keyup to blur it will work fine. I need this to run on keyup though. It will also accept .25 by itself but not a number then decimal. For example 2.25.
$(document).on('keyup', '.Monday', findTotalMon);
function findTotalMon() {
var arr = document.getElementsByClassName('Monday');
var tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseFloat(arr[i].value)) {
var newValue;
newValue = (.25 * Math.round(4 * arr[i].value));
arr[i].value = newValue;
tot += parseFloat(newValue);
}
}
document.getElementById('totalHoursMon').value = tot;
if (tot === 0) {
document.getElementById('totalHoursMon').value = '';
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input class="form-control full-width Monday" name="monday" id="monday" type="number" step="any" /><br><br>
<input class="form-control full-width totalBox" name="total" id="totalHoursMon" type="text" readonly="readonly"/>
The issue lies in the use of keyup and the overwriting of your fields value with the newly parsed / rounded float.
After typing your decimal separator, the input is parsed and rounded and the separator disappears, because "1." or "1," is parsed to 1.
One way to solve this is to only overwrite your field when the rounded input is different than the original input.
$(document).on('keyup', '.Monday', findTotalMon);
function findTotalMon() {
var arr = document.getElementsByClassName('Monday');
var originalValue, newValue, tot = 0;
for (var i = 0; i < arr.length; i++) {
originalValue = arr[i].value;
if (parseFloat(originalValue)) {
newValue = (.25 * Math.round(4 * arr[i].value));
tot += parseFloat(newValue);
if (newValue != originalValue) {
// we're only overwriting input when the rounded value is different than the original
arr[i].value = newValue;
}
}
}
document.getElementById('totalHoursMon').value = tot;
if (tot === 0) {
document.getElementById('totalHoursMon').value = '';
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input class="form-control full-width Monday" name="monday" id="monday" type="number" step="any" /><br><br>
<input class="form-control full-width totalBox" name="total" id="totalHoursMon" type="text" readonly="readonly"/>
On a side note :
Using keyup and overwriting your user's input is really annoying. For instance, while testing, I realized you can't use backspace to correct your input. I know you said you had to use keyup, but I strongly advise you to use blur or keypress. For your user's sake :)
Related
I have a shopping cart that doesn't validate cards and I'm getting a lot of declined orders because people don't catch their typos. Trying to add Luhn validation to it.
I found this script which works fine by itself. It on-the-fly changes invalid to valid when a "good" credit card number is typed in.
<input id="cc" type="text" name="creditcard" size="20"><p id="status">invalid</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$('#cc').on('input', function(){
if (checkLuhn($('#cc').val())) {
$('#status').html('valid');
} else {
$('#status').html('invalid');
}
});
function checkLuhn(value) {
// remove all non digit characters
var value = value.replace(/\D/g, '');
var sum = 0;
var shouldDouble = false;
// loop through values starting at the rightmost side
for (var i = value.length - 1; i >= 0; i--) {
var digit = parseInt(value.charAt(i));
if (shouldDouble) {
if ((digit *= 2) > 9) digit -= 9;
}
sum += digit;
shouldDouble = !shouldDouble;
}
return (sum % 10) == 0;
}
</script>
I'm trying to insert it into the HTML portion of the CGI file, below this relevant line and giving the INPUT the id="cc" tag, but the script won't run.
<INPUT TYPE="text" id="cc" NAME="Payment_Card_Number" MAXLENGTH="20" size="20" value="$form_data{'Payment_Card_Number'}">
I should work with two input values that store only Integers when I increase the value of one, the other should decrease. This must stop if the second value hit 0.
The field that contains the value to be decreased is named with ID form_val62_1, and field that can be increased by the user input is called form_val63_1. I'm calling this function onChange() cause I need to pass the ID of the form (that's cause form fields are dynamically generated depending on a PHP array length).
function check(i) {
$("#form_val63_" + i ).change(function () {
var direction = this.defaultValue < this.value;
this.defaultValue = this.value;
var val;
val = parseInt($("#form_val62_" + i).val());
if (direction) {
if (val > 0) {
$('#form_val62_' + i).val(parseInt($(this).val()) - 1);
} else {
var thvar = $(this).val();
$(this).val(thvar - 1);
}
console.log("increase 503");
console.log(val);
} else {
$('#form_val62_' + i).val(parseInt($(this).val()) + 1);
console.log("decrease 503");
console.log(val);
}
});
}
Fiddle
I got many problems here, the first decrease one time, that increase with no reason (I know there is but can't see why).
Using the solution provided by #Ph0b0x i've updated my code as
var v = $("#form_val62_" + i).val(); //Let's say this is the value from PHP....
var preVal = 0;
$("#form_val62_" + i).val(v);
$("#form_val63_" + i).on("change keyup keydown", function(event) {
let currVal = parseInt($("#form_val63_" + i).val());
console.log(preVal);
console.log(currVal);
if (currVal == 0) {
preVal = 0;
$("#form_val62_" + i).val(v);
} else if (currVal <= v) {
$("#form_val62_" + i).val((v - currVal) == 0 ? 0 : (v - currVal));
preVal = currVal;
} else {
$("#form_val63_" + i).val(v);
}
});
Now I can increase the result but when i try decrease the each value remain 0.
I guess, if i understood correctly, i will keep track of the previous value on the second input then i will start decreasing the first one until it reaches 0 and increase it until it reaches 10? Fiddle
HTML
<form>
<input id="form_val62_1" type="number" min="0" value="10" />
<input id="form_val63_1" type="number" min="0" value="0" />
</form>
JS
var v = 13; //Let's say this is the value from PHP....
var preVal = 0;
$("#form_val62_1").val(v);
$("#form_val63_1").on("change keyup keydown", function(event) {
let currVal = parseInt($("#form_val63_1").val());
console.log(preVal);
console.log(currVal);
if (currVal == 0) {
preVal = 0;
$("#form_val62_1").val(v);
} else if (currVal <= v) {
$("#form_val62_1").val((v - currVal) == 0 ? 0 : (v - currVal));
preVal = currVal;
} else {
$("#form_val63_1").val(v);
}
});
Edit: I have updated my code based on your comment. Please see this Fiddle
So bind change event handlers on both elements. I would just use data attributes so you do not have to worry about selecting by ids to bind between both.
$('[data-num-grp]').on('input', function () {
// input that was interacted with
const inp1 = $(this);
// get the group number
const grp = inp1.data('num-grp')
// select the other element with the grp
const inp2 = $('[data-num-grp="' + grp + '"]').not(inp1);
// alter the other element so it's value changes
inp2.val(this.max - this.value)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" data-num-grp="1" min="0" max="10" value="10"/>
<input type="number" data-num-grp="1" min="0" max="10" value="0"/>
<br/>
<input type="number" data-num-grp="2" min="0" max="10" value="10"/>
<input type="number" data-num-grp="2" min="0" max="10" value="0"/>
I would like to balance two input number fields using jquery based on the max value set for both. for example its like a balance, if one side goes down the other goes up and vice versa. another example if the max value is 20 then if i enter 5 in input field one then 15 would be left in input field two.
Need the help Thanks. Haven't started coding it as yet stuck trying to figure it out.
First you need to attach the input eventhandler on all of the relevant input fields. This event handler will compare the current input value of a input fields to the total/max value variable and find the remainder accordingly. The event handler then finds the other input fields and assigns them with the appropriate remainder values.
Note: This allows you to add as many inputs as you want and it will
balance them all out. Just remember to add the balance class on the
input field.
var total = 20;
$('.balance').on('input', function() {
var value = parseInt(this.value);
if (isNaN(value)) {
this.value = value = 0;
} else if (value > total) {
this.value = value = total;
}/* else if (value < 0) {
this.value = value = 0;
}
* Remove this comment if value shouldn't be negative.
*/
var remainder = total - value;
var otherInputs = $('.balance');
otherInputs.splice($.inArray(this,otherInputs),1);
var remainderDiv = remainder/otherInputs.length;
$.each(otherInputs, function(input) {
otherInputs[input].value = remainderDiv;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="balance">
<input type="number" class="balance">
Update: The two inputs can be less than the max but never higher.
var max = 20;
$('.balance').on('input', function() {
var value = parseInt(this.value);
if (isNaN(value)) {
value = 0;
}
var otherInputs = $('.balance');
var sum = 0;
$.each(otherInputs, function(input) {
sum += parseInt(otherInputs[input].value);
});
if (sum > max)
this.value = max - (sum - value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="balance">
<input type="number" class="balance">
here's a fiddle to get you started (and maybe finished):
https://jsfiddle.net/ahmadabdul3/xwyrrw53/1/
html:
<input type='number' id='first' class='balancable'/>
<input type='number' id='second' class='balancable'/>
js:
$(function() {
var max = 20;
var balanceOpposite = {
'first': 'second',
'second': 'first',
}
$('.balancable').on('input', function() {
var id = $(this).attr('id');
var thisVal = $(this).val();
$('#' + balanceOpposite[id]).val(20 - thisVal);
});
});
Below is my textbox:
<input type="number" id="payement-textbox'+index+'" name="payment-textbox" min="0" max="100000" step="any" maxlength="9" class="payment" placeholder="--" value=""/>;
There are two validation on my number type textbox. First is user cannot enter value bigger than 99999.99 which I applied successfully.
The other one is that user cannot enter more than two digits after decimal which is not working.
Here is my jQuery code:
$('input.payment').on("change paste keyup", function(event) {
var max = parseFloat($(this).attr('max'));
var num = parseFloat($(this).val());
if ( num >= max)
{
$(this).val("99999.99");
}
if( ($(this).val().indexOf('.') != -1) && ($(this).val().substring($(this).val().indexOf('.')).length > 2))
{
event.preventDefault();
}
});
Could you please tell me where I am going wrong?
Try:
$("#yourinput").keyup(function(){
var num = parseFloat($(this).val());
if ( num >= 99999.99)
{
$(this).val("99999.99");
}
var number = ($(this).val().split('.'));
if (number[1] && number[1].length > 2)
{
var salary = parseFloat($("#yourinput").val());
$("#yourinput").val( salary.toFixed(2));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<input id="yourinput" pattern="\d+">
<span id=bad style="display:none;color:red">BAD</span>
You need to use the keypress event so it will trigger before the input is entered.
This will work:
$('input.payment').on("keypress paste keyup", function(event){
//Your code
})
I need some help with javascript or jQuery.
I have three (3) input fields that I want to filter (sum of three fields).
the total value of 3 input fields is must 100. If the user fills more than 100, it will be automatically change the value that the total is 100.
you can see this example
<input type="text" name="text1" size="3"> text1<br />
<input type="text" name="text2" size="3"> text2<br />
<input type="text" name="text3" size="3"> text3<br />
<p>The maximum value of total 3 fields above is 100.</p>
<pre>example 1 :
text1 : 20;
text2 : 30;
text3 : 50; (will automatically filled with 50 because the total value must 100)</pre>
<pre>example 2 :
text1 : 37;
text2 : 60;
text3 : 3; (will automatically filled with 3 because the total value must 100)</pre>
Thanks for helping me,
I need it :)
$("input:lt(2)").on("change", function() {
var other = $("input:lt(2)").not(this).val();
if (other.length)
$("input:eq(2)").val(100 - this.value - other);
});
DEMO: http://jsfiddle.net/D5F3p/3/
This is the simplest thing I can think of!
$(document).ready(function(){
$('input[name="text2"]').blur(function(){
$('input[name="text3"]').val(100 - $('input[name="text1"]').val() - $('input[name="text2"]').val());
});
});
IMO, you can do these:
Give only two characters for both the inputs. Don't allow more than that!
You also need to check if the sum of the two inputs should not exceed 101!
Keep the input 2 readonly, until something has been entered in input 1.
Keep the input 3 always readonly.
Fiddle: http://jsfiddle.net/praveenscience/D5F3p/5/
<head>
<script type="text/javascript">
function check() {
var sum = 0;
var inputs = $(".test");
for (i = 0; i < inputs.length; i++) {
if (inputs[i].value == parseInt(inputs[i].value)) {
sum += parseInt(inputs[i].value);
if (sum > 100) {
sum -= parseInt(inputs[i].value);
inputs[i].value = 100-sum;
}
}
}
}
</script>
</head>
<body>
<input type="text" onkeyup="check()" class="test" size="3">
<input type="text" onkeyup="check()" class="test" size="3">
<input type="text" onkeyup="check()" class="test" size="3">
$(function(){
$('input[name="text1"]').keyup(function(){
var text1Value = $('input[name="text1"]').val();
if(text1Value >=100)
{
$('input[name="text1"]').val(100);
$('input[name="text2"]').val('');
$('input[name="text3"]').val('');
$('input[name="text2"]').attr('disabled','disabled');
$('input[name="text3"]').attr('disabled','disabled');
}
else
{
$('input[name="text2"]').removeAttr('disabled');
$('input[name="text3"]').removeAttr('disabled');
}
});
$('input[name="text2"]').keyup(function(){
var text1Value = parseInt($('input[name="text1"]').val());
var text2Value = parseInt($('input[name="text2"]').val());
if(isNaN(text1Value))
{
text1Value =0;
}
if(isNaN(text2Value))
{
text2Value =0;
}
var total = text1Value + text2Value;
if(total >=100)
{
$('input[name="text2"]').val(100-text1Value);
$('input[name="text3"]').val('');
$('input[name="text3"]').attr('disabled','disabled');
}
else
{
$('input[name="text3"]').removeAttr('disabled');
$('input[name="text3"]').val(100-total);
}
});
});
I am checking if sum of all text boxes if exceeding 100, then making correction in the last entered textbox with disabling the next textbox.