Keep value in input under 10 - javascript

Basically, what I want to do here is to keep the value in an input element a non-zero digit (0<x<=9). Here is my tag:
<input type="number" class="cell">
I have tried several JavaScript ideas, but none of them seem to work. I am using jQuery 3.2.1, BTW.

Here is what you are looking for:
<input type="number" class="cell" min="0" max="9" pattern="\d{0,9}">

Take a look at this example.
$('input[type=number]').keyup(function(e) {
var key = e.key
if (/[0-9]/.test(key)) {
e.target.value = key
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="cell" min="0" max="9" value="0">

There you go:
$('input[type="number"]').on('keyup click', function(){
if($(this).val() > 9){
$(this).val(9);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="cell">

You may use input event:
$('[type=number]').on('input', function(e) {
if (this.value > 9) {
this.value = this.value.split('').pop();
}
if (this.value <= 0) {
this.value = 1;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="number" class="cell">

To allow a number from 1 to 9, all you have to do is disallow anything with more than two numbers, i.e. a lenght over 1.
To disallow zero, prevent the default action when a zero is pressed
$('.cell').on('keydown', function(e) {
this.value = this.value.slice(1);
if (e.which === 48 || e.which === 96) e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="cell">

Here you go with the solution https://jsfiddle.net/pj0L78sm/3/
$('input[type="number"]').attr({
max: 10,
min: 0
});
$('input[type="number"]').keydown(function(e){
var value = $(this).val() + (parseInt(String.fromCharCode(e.which)) || 0);
if(e.which != 8 && (parseInt(value) < 0 || parseInt(value) > 10) || e.which === 189){
e.preventDefault();
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="cell">
I have kept limit as 0 to 10 and also used jQuery 3.2.1 in jsFiddle.

Related

How to clamp an Input[type="range"]

I want the slider to not pass a certain limit. How can I set this is HTML and also change it in javascript?
<input type="range" min="0" max="100" value="30">
I want to set it so that the slider can never go past a certain value though the value will be there on slider i.e slider should have min:0 max:100 but never go past say 70.
this could work for your case, but set the max value to 70 is better in my opinion.
function test(e, el) {
if (e.target.value > 70) el.value = 70;
document.querySelector("h1").innerHTML = "range value: " + e.target.value;
}
<input type="range" min="0" max="100" style="width: 100%;" oninput="test(event, this)">
<br>
<h1>range value: 50</h1>
Here's a solution for you. If the user drags the slider over to 70, we reset it to 70 again.
<h1>Display a Range Field</h1>
<label for="vol">Volume <span id="currentvalue"> </span> (between 0 and 100):</label>
<input type="range" id="vol" name="vol" min="0" max="100" value="30">
<script type="text/javascript">
document.getElementById("currentvalue").innerHTML = document.getElementById("vol").value;
document.getElementById("vol").addEventListener("change", function(e){
if(e.target.value > 70) {
alert("You can't pick above 70 for now!");
this.value = 70;
}
document.getElementById("currentvalue").innerHTML = e.target.value;
e.preventDefault();
e.stopPropagation();
})
</script>

Adding comma Separators for a value after a calculation

The calculation , i have setup 2 input fields where multiplication will take place. The text boxes will accept number input , while displaying comma separation to the value.Before the multiplication, i remove the commas and then pass the result to text box 3. How can i show the answer to the end user with comma separation for below instance ? Appreciate your great help.
function calculate() {
var E1 = $("#E1").val().split(",").join("");
var E2 = $("#E2").val().split(",").join("");
var result = E1*E2;
$("#E3").val(result);
}
//For comma seperation
$('input.number').keyup(function(event) {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label>Value 01</label>
<input class="form-control number" type="tel" id="E1" required oninput="calculate()" />
</div>
<div class="form-group">
<label>Value 02</label>
<input class="form-control number" type="tel" id="E2" required oninput="calculate()" />
</div>
<div class="form-group">
<label>Value 03 (Result)</label>
<input class="form-control number" type="tel" id="E3" />
</div>
Just added digits function this function return make comma for every three digits. Hope this help you.
function calculate() {
var E1 = $("#E1").val().split(",").join("");
var E2 = $("#E2").val().split(",").join("");
var result = E1 * E2;
$("#E3").val(result);
$("#E3").digits();
}
$.fn.digits = function() {
return this.each(function() {
$(this).val($(this).val().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
})
}
//For comma seperation
$('input.number').keyup(function(event) {
// skip for arrow keys
if (event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label>Value 01</label>
<input class="form-control number" type="tel" id="E1" required oninput="calculate()" />
</div>
<div class="form-group">
<label>Value 02</label>
<input class="form-control number" type="tel" id="E2" required oninput="calculate()" />
</div>
<div class="form-group">
<label>Value 03 (Result)</label>
<input class="form-control number" type="tel" id="E3" />
</div>
function calculate() {
var E1 = $("#E1").val().split(",").join("");
var E2 = $("#E2").val().split(",").join("");
var result = E1*E2;
$("#E3").val(result);
formatNumber($("#E3"))
}
function formatNumber(input) {
// format number
input.val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
;
});
//For comma seperation
$('input.number').keyup(function(event) {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
formatNumber($(this))
});

Increase and decrease check not working by 10, 100, 1000 and so on

I try to check if my input increases or decreases, this works fine except for the numbers 10, 100, 1000 and so on. I've tried several code's but none of them will work.
Here are some examples:
$(document).ready(function(){
var professional = $("#professional");
var oldValue = professional.val();
professional.data("oldValue", oldValue);
$("#professional").change(function(){
var oldValue = $(this).data("oldValue");
var newValue = $(this).val();
if (newValue > oldValue)
alert("increase!");
else
alert("decrease!");
$(this).data("oldValue", newValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="quantity">
<label for="professional">Professional</label><br>
<input type="number" class="price" id="professional" min="0" value="9">
</div>
$(document).ready(function() {
$("#professional").attr('data-prev-val', $("#professional").val());
$("#professional").change(function() {
var newValue = $(this).val();
if (newValue > $(this).attr('data-prev-val'))
alert("increase!");
else
alert("decrease!");
$("#professional").attr('data-prev-val', newValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="quantity">
<label for="professional">Professional</label><br>
<input type="number" class="price" id="professional" min="0" value="9">
</div>
There are other ways, but they all have the same problem. Does anyone know why this is and how it can be solved?
It's because you're comparing the value alphabetically rather than numerically
try this:
var oldValue = Number($(this).data("oldValue"));
var newValue = Number($(this).val());
if (newValue > oldValue) ...
You should use parseInt because currently value consider as string.
$(document).ready(function() {
$("#professional").attr('data-prev-val', $("#professional").val());
$("#professional").change(function() {
var newValue = parseInt($(this).val());
if (newValue > parseInt($(this).attr('data-prev-val')))
alert("increase!");
else
alert("decrease!");
$("#professional").attr('data-prev-val', newValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="quantity">
<label for="professional">Professional</label><br>
<input type="number" class="price" id="professional" min="0" value="9">
</div>

Input tag type number for credit card

I have 4 input tags.
<input type="number" class="br1" name="first">
<input type="number" class="br1" name="secound">
<input type="number" class="br1" name="third">
<input type="number" class="br1" name="fourth">
I want to set maxlength (4 numbers) for every input tag. I tried to set maxlength but it doesn't work. Also, when I enter 4 numbers in one input tag, I want to automaticlly input in next input tag.
Thanks.
If you want to use maxlength change type of input to text. Then you can parse all you your inputs strings to a number.
$(".br1").keyup(function () {
if (this.value.length == this.maxLength) {
var $next = $(this).next('.br1');
if ($next.length)
$(this).next('.br1').focus();
else
$(this).blur();
}
});
$(".btn").click(function() {
var string = "";
$(".br1").each(function() {
string += this.value;
});
number = parseInt(string);
console.log(number);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="br1" name="first" maxlength=4>
<input type="text" class="br1" name="secound" maxlength=4>
<input type="text" class="br1" name="third" maxlength=4>
<input type="text" class="br1" name="fourth" maxlength=4>
<button class="btn">toNumber</button>
Use max="9999" and min="0000" to set the maximum value for input type number.
As per http://w3c.github.io/html/sec-forms.html#the-maxlength-and-minlength-attributes maxlength is not valid for input of type number.
You can use input event attached to .br1 elements, .slice() with parameters 0, -1 to remove character if .length of .value is greater than 4
var inputs = document.querySelectorAll(".br1");
for (let input of inputs) {
input.oninput = () => {
if (input.value.length > 4) {
input.value = input.value.slice(0, -1)
}
}
}
<input type="number" class="br1" name="first">
<input type="number" class="br1" name="secound">
<input type="number" class="br1" name="third">
<input type="number" class="br1" name="fourth">
You can do this using only javascript. Also note the maxLength attribute don't work on number, so you may need to use input type='text'
Here is snippet
// get the input
var inputBox = document.getElementsByClassName("br1")
// loop through the array of input
for (var i = 0; i < inputBox.length; i++) {
// creating a closure
(function(x) {
// adding event listener to each of the input
inputBox[x].addEventListener('keydown', function(x) {
// checking value of maxLength
var maxLength = parseInt(this.attributes["maxlength"].value, 10);
// length of the input value
var myLength = this.value.length;
// if both are equal then find the next sibling
if (myLength >= maxLength) {
var next = this.nextElementSibling
// if the next sibling is input, set focus to it
if (next.tagName.toLowerCase() === "input") {
next.focus();
}
}
})
}(i))
}
It as simple as posible, Try this:
$("input[type=number]").keypress(function (e) {
var el = $(this);
var currentValue = el.val();
var char = String.fromCharCode(e.keyCode || e.which);
if (currentValue.length === 3) {
el.val(currentValue + char);
e.preventDefault();
el.next().focus();
} else if (currentValue.length >= 4) {
e.preventDefault();
}
})
input[type=number]{
width:60px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="number" class="br1" name="first">
<input type="number" class="br2" name="first">
<input type="number" class="br3" name="first">
<input type="number" class="br4" name="first">

Add and multiply values using jquery

I have 2 products and wanted to multiply with quantity and add up both price along with tax and to show the final price of both added and multiplied values I tried doing using jQuery but I am unable to multiply and add up both values can any one help me out
Here is the code for it:
$(document).ready(function(){
$('#sticker01').on('keyup', function() {
var sticker_01 = $('#sticker01').val();
var oldval = parseInt($('#order_total').text());
var total_val = (sticker_01 * 8 +1.30) + oldval;
$('#order_total').html(total_val);
});
});
$(document).ready(function(){
$('#sticker02').on('keyup', function() {
var sticker_02 = $('#sticker02').val();
var oldval = parseInt($('#order_total').text());
var total_val = (sticker_02 * 2 + 1.30) + oldval;
$('#order_total').html(total_val);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="form-group">
<label>MadEnoughToPayAttention Bumper Sticker</label>
<input type="number" name="bumper_sticker_01_qty" id="sticker01">
</div>
<div class="form-group">
<label>ChangeNotHope Bumper Sticker</label>
<input type="number" name="bumper_sticker_02_qty" id="sticker02">
</div>
<div class="order_total">
<span>Order Total : $<div id="order_total">0.00</div></span>
</div>
Here is a less verbose solution to your issue with minor changes to the HTML and a complete overhaul of the Javascript.
HTML:
I added the min attribute and set its value to 0 to prevent the input spinners from selecting negative values in both the sticker01 and sticker02 elements. I also set the order_total input to disabled as this is the calculation field which will get its value from the inline Javascript. These udpates are cosmetic and play no roll in the structural performance your app.
<div class="form-group">
<label>MadEnoughToPayAttention Bumper Sticker</label>
<input type="number" name="bumper_sticker_01_qty" min="0" id="sticker01">
</div>
<div class="form-group">
<label>ChangeNotHope Bumper Sticker</label>
<input type="number" name="bumper_sticker_02_qty" min="0" id="sticker02">
</div>
<div class="order_total">
<span>Order Total : $
<input type="text" name="bumper_sticker_total" id="order_total" disabled>
</span>
</div>
Javascript:
Here you can implement an anonymous function to handle the events .keyup() and .change() and use a delegated event on the input elements.
$('input').on('change keyup', function() {
sticker_01 = $('#sticker01').val(),
sticker_02 = $('#sticker02').val(),
total_val = $('#order_total');
if ((sticker_01) > 0 && (sticker_02) == 0) {
total_val.val(((sticker_01) * 8 + 1.30).toFixed(2));
} else if ((sticker_02) > 0 && (sticker_01) == 0) {
total_val.val(((sticker_02) * 2 + 1.30).toFixed(2));
} else if ((sticker_01) > 0 && (sticker_02) > 0) {
total_val.val(((((sticker_01) * 8 + 1.30) + ((sticker_02) * 2 + 1.30)).toFixed(2)));
} else {
total_val.val('');
};
});
That's everything you need. Here is a sample Code Snippet for your review.
$('input').on('change keyup', function() {
sticker_01 = $('#sticker01').val(),
sticker_02 = $('#sticker02').val(),
total_val = $('#order_total');
if ((sticker_01) > 0 && (sticker_02) == 0) {
total_val.val(((sticker_01) * 8 + 1.30).toFixed(2));
} else if ((sticker_02) > 0 && (sticker_01) == 0) {
total_val.val(((sticker_02) * 2 + 1.30).toFixed(2));
} else if ((sticker_01) > 0 && (sticker_02) > 0) {
total_val.val(((((sticker_01) * 8 + 1.30) + ((sticker_02) * 2 + 1.30)).toFixed(2)));
} else {
total_val.val('');
};
});
<div class="form-group">
<label>MadEnoughToPayAttention Bumper Sticker</label>
<input type="number" name="bumper_sticker_01_qty" min="0" id="sticker01">
</div>
<div class="form-group">
<label>ChangeNotHope Bumper Sticker</label>
<input type="number" name="bumper_sticker_02_qty" min="0" id="sticker02">
</div>
<div class="order_total">
<span>Order Total : $
<input type="text" name="bumper_sticker_total" id="order_total" disabled>
</span>
</div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

Categories