How to pattern html5 input - javascript

I have input like this
<input max="100" min="0" type="number">
But in this input users can put numbers like 01 02 03 004 itp...
And my question is how to prevent this? To only numbers from 0 to 100
0, 1, 2, 3 ... 100

In most cases JavaScript is the answer:
<input type="text" id="taskinput">
<script>
const input = document.getElementById('taskinput');
let lastValue = '';
input.oninput = () => {
if (!input.value) {
lastValue = '';
return;
}
const val = parseInt(input.value);
if (val > 100 || isNaN(val)) {
input.value = lastValue;
return;
}
lastValue = val;
input.value = lastValue;
}
</script>

You could archive this by adding a onchange eventlistener on the input.
The regex will remove the leading zero.
document.getElementById('number').onchange = function(){
this.value = this.value.replace(/\b0+[0-9]/g, '');
};
<input id="number" min="0" max="100" step="1" type="number" >

Related

Adding 2 input values on keyup to get the answer in the 3rd input box

i know this has been asked before but i can't seem to get this right. I need to take input values from two text boxes and add it to another and that answer should appear in the 3rd textbox after both boxes are typed in. Nothing seems to be happening however though. Thanks
Here's the HTML
//Input 1
<input name="attribute_campaign_addon_one_time_cost_value" id="am_attribute_campaign_addon_one_time_cost_value">
//Input 2
<input name="attribute_campaign_addon_total_monthly_cost_value" id="attribute_campaign_addon_total_monthly_cost_value">
//Input 3 where added answer should go
<input name="attribute_campaign_addon_total_monthly_cost_calculated_value" id="am_attribute_campaign_addon_total_monthly_cost_calculated_value" value="">
//JQ
var $oneTimeCostField = $('#am_attribute_campaign_addon_one_time_cost_value');
var $recurringTotalCostField = $('#am_attribute_campaign_addon_total_monthly_cost_value');
var $totalRetailAmountField = $('#am_attribute_campaign_addon_total_monthly_cost_calculated_value');
function calcVal() {
var num1 = $oneTimeCostField.val();
var num2 = $recurringTotalCostField.val();
var result = parseInt(num1) + parseInt(num2);
if (!isNaN(result)) {
$totalRetailAmountField.val() = result;
}
}
calcVal();
$(num1, num2).on("keydown keyup", function() {
calcVal();
});
Your selector for the onkeyup/down is wrong, and your total field has the wrong id.
The result can be set like this: $totalRetailAmountField.val(result);
//JQ
var $oneTimeCostField = $('#am_attribute_campaign_addon_one_time_cost_value');
var $recurringTotalCostField = $('#am_attribute_campaign_addon_total_monthly_cost_value');
var $totalRetailAmountField = $('#am_attribute_campaign_addon_total_monthly_cost_calculated_value');
function calcVal() {
var num1 = $oneTimeCostField.val();
var num2 = $recurringTotalCostField.val();
var result = parseInt(num1, 10) + parseInt(num2, 10);
console.log("calcVal ", num1,num2, result);
if (!isNaN(result)) {
$totalRetailAmountField.val(result);
}
}
calcVal();
$oneTimeCostField.on("keydown keyup", function() {
calcVal();
});
$recurringTotalCostField.on("keydown keyup", function() {
calcVal();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
//Input 1
<input name="attribute_campaign_addon_one_time_cost_value" id="am_attribute_campaign_addon_one_time_cost_value">
//Input 2
<input name="attribute_campaign_addon_total_monthly_cost_value" id="am_attribute_campaign_addon_total_monthly_cost_value">
//Input 3 where added answer should go
<input name="attribute_campaign_addon_total_monthly_cost_calculated_value" id="am_attribute_campaign_addon_total_monthly_cost_calculated_value" value="">
http://api.jquery.com/val/
Jquery input value is set as follows:
$totalRetailAmountField.val(result);
First thing, I have never seen name & id such big value. this is not only cause problem in readability but also introduce error like unwanted space in id
Secondly num1 & num2 are already jquery object then what is the use of $(num1, num2)
Thirdly update the value of the third input by passing the vale as function argument $totalRetailAmountField.val(result);
var $oneTimeCostField = $('#am_attribute_campaign_addon_one_time_cost_value');
var $recurringTotalCostField = $('#attribute_campaign_addon_total_monthly_cost_value');
var $totalRetailAmountField = $('#am_attribute_campaign_addon_total_monthly_cost_calculated_value');
function calcVal() {
var num1 = $oneTimeCostField.val();
var num2 = $recurringTotalCostField.val();
var result = parseInt(num1) + parseInt(num2);
if (!isNaN(result)) {
$totalRetailAmountField.val(result);
}
}
$('#attribute_campaign_addon_total_monthly_cost_value,#am_attribute_campaign_addon_one_time_cost_value').on("keydown keyup", function() {
calcVal();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="attribute_campaign_addon_one_time_cost_value" id="am_attribute_campaign_addon_one_time_cost_value">
<input name="attribute_campaign_addon_total_monthly_cost_value" id="attribute_campaign_addon_total_monthly_cost_value">
<input name="attribute_campaign_addon_total_monthly_cost_calculated_value" id="am_attribute_campaign_addon_total_monthly_cost_calculated_value" value=" ">
This is a fairly verbose solution to your query.
Listen to change on each input and apply their respective values to the final answer input (input#fa)
const a1 = document.querySelector('#a1')
const a2 = document.querySelector('#a2')
const fa = document.querySelector('#fa')
const answers = []
const _handleFinalAnswer = () => (fa.value = (+answers[0] || 0) + (+answers[1] || 0))
a1.addEventListener('change', e => {
const { value } = e.target
answers[0] = value
_handleFinalAnswer()
})
a2.addEventListener('change', e => {
const { value } = e.target
answers[1] = value
_handleFinalAnswer()
})
<input type="number" step="any" name="answer 1" id="a1" />
<input type="number" step="any" name="answer 2" id="a2" />
<input name="final answer" id="fa" />
Or here is a more dynamic way to calculate all possible amount of inputs to achieve a final sum but it could still be done with two inputs :-)
const answersInputs = document.querySelectorAll('input.answer')
const finalAnswer = document.querySelector('#fa')
const _getSummedValues = () => (
[...answersInputs]
.map(input => +input.value || 0)
.reduce((prev, curr) => prev+curr, 0)
)
const _setFinal = () => finalAnswer.value = _getSummedValues()
answersInputs.forEach(input => input.addEventListener('change', _setFinal))
<input type="number" step="any" name="answer 1" class="answer" />
<input type="number" step="any" name="answer 2" class="answer" />
<input type="number" step="any" name="answer 3" class="answer" />
<input type="number" step="any" name="answer 4" class="answer" />
<input type="number" step="any" name="answer 5" class="answer" />
<input type="number" step="any" name="answer 6" class="answer" />
<input type="number" step="any" name="answer 7" class="answer" />
<input name="final answer" id="fa" />

How to check html slider values in Javascript? (either value-1 or value+1)

I have this slider in HTML and I was wondering how to check if the previous value of the slider is equal with the current value. Please if you know how to do this let me know. Thanks for your time.
var target = document.getElementById("myTarget");
let previous;
function foo(myValue) {
//console.log(myValue);
//Update SPAN
target.innerHTML = myValue; //EXPECTED = CURRENT VALUE
console.log(previous);
if(previous === myValue){
//Statements
console.log("same");
}else{
//Statemets
//previous = myValue;
console.log("different");
}
}
<input id="mySlider" type="range" value="0" min="0" max="5" step="1" oninput="foo(this.value);">
<span id="myTarget">0</span>
const slider = document.getElementById('mySlider');
const output = document.getElementById('output');
var initialValue = 2; // set however you want
slider.addEventListener('input', function (event) {
let outcome = "'"+initialValue+"' and '"+this.value+"' are ";
if( parseInt(this.value)===initialValue){
outcome+= "equal!"
} else{
outcome+= "not equal"
}
output.innerHTML = outcome
}, false);
<input id="mySlider" type="range" value="0" min="0" max="5" step="1"/>
<div id="output">
<em>Not run yet</em>
</div>
Thanks to #Martijn answer I was able to create a loop like this:
var slider = document.getElementById("slider-element_BV");
slider.addEventListener('input', function(event){
RAYS_CLASS.Ray_Techniques.RAYS_TECHNIQUES_MANAGER.BV().BV_REMOVE();
for(var i=this.min; i<=this.max; i++) {
if(parseInt(this.value) === i){
RAYS_CLASS.Ray_Techniques.RAYS_TECHNIQUES_MANAGER.BV().BV_Subdivide(i);
}
}
});

Decrease numeric input value when increasing another input value

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"/>

Auto substract both values from 100

I created two input fields where they should substract from each other keeping a max value at 100.
Currently it substracted value is shown in the second value. I want it to be interchangeable. Irrespective of whether I put in first or second input field, the answer shows in the other.
Could someone help?
function updateDue() {
var total = parseInt(document.getElementById("totalval").value);
var val2 = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val2) { val2 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val2;
var val1 = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val1) { val1 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val1;
}
<input type="hidden" id="totalval" name="totalval" value="100" onchange="updateDue()">
<div>
Enter Value:
<input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue()">
</div>
<div>
Substracted:
<input type="text" name="remainingval" class="form-control" id="remainingval" onchange="updateDue()">
</div>
The simple way to achieve this would be to group the inputs by class and attach a single event handler to them. Then you can take the entered value from 100, and set the result to the field which was not interacted with by the user. To do that in jQuery is trivial:
$('.updatedue').on('input', function() {
var total = parseInt($('#totalval').val(), 10) || 0;
var subtracted = total - (parseInt(this.value, 10) || 0);
$('.updatedue').not(this).val(subtracted);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="totalval" name="totalval" value="100" />
<div>
Enter Value:
<input type="text" name="inideposit" class="updatedue form-control" id="inideposit" />
</div>
<div>
Subtracted:
<input type="text" name="remainingval" class="updatedue form-control" id="remainingval" />
</div>
You can easily validate this so that outputs < 0 and > 100 can be discounted, if required.
Edit your code as below
function updateDue(box) {
var total = parseInt(document.getElementById("totalval").value);
if(box == 1){
var val = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val) { val = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val;
}else if(box == 2){
var val = parseInt(document.getElementById("remainingval").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val) { val = 0; }
var ansD = document.getElementById("inideposit");
ansD.value = total - val;
}
}
<input type="hidden" id="totalval" name="totalval" value="100" onchange="updateDue(0)">
<div>
Enter Value:
<input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue(1)">
</div>
<div>
Substracted:
<input type="text" name="remainingval" class="form-control" id="remainingval" onchange="updateDue(2)">
</div>

How to prevent user to enter more than two digit after decimal?

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
})

Categories