html input field set range - javascript

What is the most efficient way to set the range for an input-field to -100.0 to 100.0? I would like to check every character. Other characters than -,0,1,2,3,4,5,6,7,8,9 and . are not allowed. Values without floating point, e.g. 78, are also possible.
UPDATE
I need a solution for IE, so html5 solution with type="range" or type="number" are useless for me.
The only code I have is the input field:
<input type="text" id="zahlenwert" value="" />
The question is: Do I have to check every character with onKeydown() or is there a smarter way?

Here is what you are looking for:
http://jeroenvanwarmerdam.nl/content/resources/javascript/jquery/spincontrol/jquery-spincontrol-1.0.zip
And here is example:
http://jeroenvanwarmerdam.nl/content/resources/javascript/jquery/spincontrol/jquery-spincontrol.html?x=31&y=10
Integration:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="jquery-numeric.js"></script>
<script type="text/javascript" src="jquery-number-selector.js"></script>
<script type="text/javascript" src="jquery-spincontrol-support.js"></script>
<script type="text/javascript" src="jquery-spincontrol.js"></script>
<!-- SpinControl definition -->
<script type="text/javascript">
(function($) {
$(function() {
$(":number").addClass("number").spinControl({ folder: "images/" });
});
})(jQuery);
</script>
Here is your body html code:
<input type="number" max="10" min="-10" step="0.5" />

I'm partly guessing at your requirements but if you're just trying to restrict the input value to a number within a specific range you could use HTML5's range input type:
<input type="range" name="myrange" min="-100" max="100">
Or use JavaScript to validate the value like in this demo fiddle:
document.getElementById('test').onchange = isNumber;
function isNumber(){
var val = this.value;
var aNumber = !isNaN(val);
var aNumberNotOverOneHundred = (Math.abs(parseFloat(val, 10)) <= 100);
alert((aNumber && aNumberNotOverOneHundred)?"Yarp":"Narp");
}
Or use input pattern attribute to validate against a regex pattern.

This is the solution I wanted:
$(document).ready(function() {
$("input#zahlenwert").keyup(function(){
var zahlenwert= $("input#zahlenwert").val();
var status = 0;
for(i=zahlenwert.length;i>0;i--){
if(status==0){
if(zahlenwert.length == 0){
}
else if(zahlenwert.length == 1 && zahlenwert.match(/^(-|[0-9]) /)!=null){
status = 1;
console.log("zahlenwert ok");
}
else if(zahlenwert.length == 2 && zahlenwert.match(/^(-[0-9]|[0-9],|[1-9][0-9])/)!=null){
status = 1;
console.log("zahlenwert ok");
}
else if(zahlenwert.length == 3 && zahlenwert.match(/^(-[1-9][0-9]|[0-9],[0-9]|100|[1-9][0-9],|-[0-9],)/)!=null){
status = 1;
console.log("zahlenwert ok");
}
else if(zahlenwert.length == 4 && zahlenwert.match(/^(-100|100,|[1-9][0-9],[0-9]|-[0-9],[0-9]|-[1-9][0-9],)/)!=null){
status = 1;
console.log("zahlenwert ok");
}
else if(zahlenwert.length == 5 && zahlenwert.match(/^(100,0|-100,|-[1-9][0-9],[0-9])/)!=null){
status = 1;
console.log("zahlenwert ok");
}
else if(zahlenwert.length == 6 && zahlenwert.match(/^-100,0/)!=null){
status = 1;
console.log("zahlenwert ok");
}
else{
zahlenwert = zahlenwert.substring(0,zahlenwert.length-1);
$("input#zahlenwert").val(zahlenwert);
console.log("Error!!!");
}
}
}
});
});

Related

Using jQuery for user registration form validation

I'm trying to create a website for learning/exercise but I'm stuck at user registration validation. There's no error message and nothing happens.
Here is a JsFiddle Link.
Also I tried:
if(user_name.length < 3 && user_name!=="")
and
if(user_name.length < 3)
Code snippet:
var user_name = $('#username').val();
$('#username').on('keyup',function(){
if(user_name.length < 3 && user_name!=""){
$('#username-info').html('Username must be at least 3 characters.');
}
else if(user_name.length > 3){
$('#username_info').html('No problem');
}
});
#username-info {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="username">
<p id="username-info"></p>
The keyup functions need to trigger on the input field.
The keyup functions updates the username (else it will be the same).
$('#username').on('keyup',function(){
var user_name = $('#username').val();
if(user_name.length < 3 && user_name!=""){
$('#username-info').html('Username must be at least 3 characters.');
}
else if(user_name.length >= 3){
$('#username-info').html('No problem');
}
});
I think you have just put wrong ids AND your variable user_name is only initialized one time on start, so its value is always empty.
$('#username').on('keyup', function() {
var user_name = $(this).val();
if (user_name.length < 3 && user_name != "") {
$('#username-info').html('Username must be at least 3 characters.');
} else if (user_name.length > 3) {
$('#username-info').html('No problem');
}
});
#username-info {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="username">
<p id="username-info">
</p>
I use your code as reference and made some changes in it for better output.
You can try this, here i am changing color code as well for the error message so you will get better result.
$('#username').on('keyup',function(){
var user_name = $('#username').val();
if(user_name.length < 3 && user_name != ""){
$('#username-info').html('Username must be at least 3 characters.');
$('#username-info').addClass('username-info');
$('#username-info').removeClass('username-info-2');
}
else if(user_name.length >= 3){
$('#username-info').html('No problem');
$('#username-info').addClass('username-info-2');
$('#username-info').removeClass('username-info');
}
});
.username-info {
color: red;
}
.username-info-2 {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="username">
<p id="username-info"></p>
Currently, user_name is declared once at the start of your script, so it will never be updated.
Then, you attached a keyup event handler on <p#username-info>, not <input#username>, so when you input something into it, nothing will be triggered.
So, you need to update user_name at each input into <input#username>.
// Here, you need to attach the event handler of #username, not #username-info.
$('#username').on('keyup', function() {
// And here, you get the value of your input.
let user_name = $('#username').val();
// let user_name = $(this).val(); works too.
// Writing "(user_name)" in a condition is the same as "(user_name !== '')".
if (user_name && user_name.length < 3) {
$('#username-info').html('Username must be at least 3 characters.');
} else if (user_name.length >= 3) {
// You wrote "#username_info" instead of "#username-info" here.
$('#username-info').html('No problem');
}
});
#username-info {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="username">
<p id="username-info">
</p>
you have a lot of typos in your script and you looked for the paragraph on key up not your input field.
var user_name = "";
$('#username').on('keyup',function(){
user_name = $('#username').val();
if(user_name.length <= 3 && user_name!=""){
$('#username-info').html('Username must be at least 3 characters.');
}
else if(user_name.length > 3){
$('#username-info').html('No problem');
}
});

If input maxlength is reached do something

I have a maxlength of 11 for an input field. I would like to perform a jQuery function when the maxlength has been met and the user keeps trying to type, so instead of it not doing anything, it'd show a message.
Please could you give me some pointers?
Thanks in advance!
Try this: IT will alert a message when the user hits 11 characters.
$("input").on("keyup",function() {
var maxLength = $(this).attr("maxlength");
if(maxLength == $(this).val().length) {
alert("You can't write more than " + maxLength +" chacters")
}
})
Demo
$("input").on("keyup",function() {
var maxLength = $(this).attr("maxlength");
if(maxLength == $(this).val().length) {
alert("You can't write more than " + maxLength +" chacters")
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input maxlength="11" />
try this code
$(document).ready(function() {
$("#text").keypress(function(e) {
var length = this.value.length;
if (length >= 11) {
e.preventDefault();
alert("not allow more than 11 character");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text">
You are looking for something like:
$("input").keypress(function(e){
if(e.target.value.length==11){
alert("maxlength reached");
}
});
Obviously change to use the correct selector and alert/modal popup.
$(document).ready(function(){
$("input").keyup(function(){
var a = $(this).val().length;
if(a >= 11){
$(this).attr('maxlength','11')
alert("not allowed")
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input>
If you add the $(document) it will find all the inputs with maxlength attribute, even if you have created them after loading the page.
$(document).on("input keypress", "input[maxlength]", function (e) {
var $input = $(e.currentTarget);
if ($input.val().length >= $input.attr("maxlength")) {
alert("Max length reached")
}
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<input>

if input has reached 7 digits, stop the function

So basically I have a button .button, which adds a number to my input #number everytime it's pressed.
Now, when I already have 7 digits in my input #number, I want the function to like 'stop working'.
Here is my code (works fine):
function nrtwo(hello){
var das = $(hello).html();
var tempNum = $("#number").val();
$("#number").val(tempNum + '' + das);
tempNum = null;
};
$(".button").click(function(){
nrtwo(this);
});
I was thinking of something like this?
if ($("#number").attr('maxlength') == '7') {
return false;
}
Thanks for the help.
Try this .length it is a Number and unblind click event when you reach 7 digits :
Working jsFiddle
$(".button").click(function(){
if ($("#number").val().length == 7) {
$(this).unbind('click');
return false;
}else{
nrtwo(this);
}
});
You need to handle this scenario in the click event itself. Please see the following example:
$(".button").click(function(){
if ($("#number").val().length <= 7) {
nrtwo(this);
}
});
This will only call the nrtwo method only when the input's length is less than or equals to 7.
If you are handling numbers only, you can also check the numeric value before adding to it.
$('#add').click(function() {
var value = parseInt($('#output').val());
if(value <= 999999) {
$('#output').val(value + 1);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add">Add</button>
<input type="text" id="output" value="999995" />
$('#number').keypress(function(event){
var n = $(this).val();
if(n.length == 7){
event.preventDefault(); //stop character from entering input
}
if(event.which != 8 && isNaN(String.fromCharCode(event.which))){
event.preventDefault(); //stop character from entering input
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<input id="number"/>
One method is to use .length property.
Please try this:
if ($("#number").val().length == '7') {
return false;
}
$('#add').click(function() {
if ($("input").val().length != '7') {
$('input').val(parseInt($('input').val())+1);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" value="999998"/>
<button type="button" id="add">Add</button>

JavaScript RegEX Test not working

I want to check if input text (amount) is between 1-100 or not but regex test not working.
here is my JS code
<script type="text/javascript" >
console.log(document.getElementById("amount").value); // 222
var regex = /^(100)|[1-9]\d?$/;
if(regex.test(document.getElementById("amount").value))
{
alert('validated')
}
else
alert('error')
</script>
Wrap the code in DOMContentLoaded event callback
Don't use RegEx. Use comparison operators
Code:
document.addEventListener('DOMContentLoaded', function () {
// Get the value & convert it into Number
var value = parseInt(document.getElementById('amount').value, 10);
// Value between 0 & 100
if (value > 0 && value <= 100) {
alert('Valid');
} else {
alert('Error');
}
});
It would be enough to use parseInt() function or Number constructor to perform such a simple validation:
<script type="text/javascript" >
var amount = Number(document.getElementById("amount").value); // 222
alert ((amount > 0 && amount <= 100)? 'Valid' : 'Invalid');
</script>
If you really want to use regex, this should work:
/^100$|^[1-9]\d?$/
It doesn't allow eg 09, but maybe that's OK.
<html>
<head>
<script>
function validateValue()
{
var amount = document.getElementById('testId').value;
if((isNaN(amount ))){
document.getElementById("errorId").style.display= "";
}
else
{
if(amount>100){
document.getElementById("errorId").style.display= "";
}
else
{
document.getElementById("errorId").style.display= "none";
}
}
}
</script>
</head>
<body>
Enter 1 to 100:<input type="text" onkeyup="validateValue()" id="testId"/>
<span id="errorId" style="color:red;display:none"> Not a valid amount</span>
</body>
</html>

Using JQuery to Control the Range of Textboxes

using JQuery, I am trying to create a few textboxes that will only allow numeric values, no duplicate numbers, no empty spaces and allow only numbers in the range. I used the range from 1 to 999. This is my code so far. I have the numeric values and the duplication of numbers parts working but I am not sure how to prevent empty textboxes or maintain the range from 1 to 999 for each textbox. The range part does not seem to work and I haven't figured out how to prompt the user about empty textboxes yet. I think there is a way to use HTML5 to control the range but that method won't prompt the user if they are not within the range. Do you have any suggestions?
<html>
<head>
<script type='text/javascript' src='js/jquery.js'></script>
</head>
<form id="form1">
Enter some text: <input type="text" id="field1" />
<br /><br />
Enter some text: <input type="text" id="field2" />
<br /><br />
Enter some text: <input type="text" id="field3" />
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#field1').blur(function() {
if ($(this).val() == $('#field2').val() || $(this).val() == $('#field3').val()) {
$('#field1').stop(false,true).after(' <span style="color:red;" class="error">No duplicate values please!</span>');
$('.error').delay(600).fadeOut();
$(this).val('');
}
});
$('#field2').blur(function() {
if ($(this).val() == $('#field1').val() || $(this).val() == $('#field3').val()) {
$('#field2').stop(false,true).after(' <span style="color:red;" class="error">No duplicate numbers please!</span>');
$('.error').delay(600).fadeOut();
$(this).val('');
}
});
$('#field3').blur(function() {
if ($(this).val() == $('#field1').val() || $(this).val() == $('#field2').val()) {
$('#field3').stop(false,true).after(' <span style="color:red;" class="error">Duplicate values are not allowed!</span>');
$('.error').delay(600).fadeOut();
$(this).val('');
}
});
});
function RangeTextBox(min, max) {
this.min = min;
this.max = max;
this.textboxbody = $("<input type='text'>");
// Check for a valid range
this.textboxbody.keyup(function(event) {
var textboxbody = event.target;
var value = parseInt(textboxbody.value);
var isNotNumeric = !/^[0-9]+$/.test(textboxbody.value);
var isOutsideRange = (value < min) || (value > max);
if (isNotNumeric || isOutsideRange) {
$(textboxbody).addClass('error');
}
else {
$(textboxbody).removeClass('error');
}
});
return this.textboxbody;
}
<!-- To use it in, simple create a new TextBox by calling new RangeTextBox(min, max). For example -->
$(document).ready(function() {
$("textboxbody").append(new RangeTextBox(1, 999));
});
</script>
</html>
$(document).ready(function() {
$("textboxbody").append(RangeTextBox(1, 999));
});
I would suggest you to use jquery validation plugin: http://docs.jquery.com/Plugins/Validation

Categories

Resources