JavaScript RegEX Test not working - javascript

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>

Related

How to call a function containing If/Else using User Input in JavaScript

How do I go about nesting an If/Else statement into a function and then calling that function using a user input in the body in order to make the function calculate the correct alert with JavaScript? I'm missing the knowledge of how to call the statement in the body it seems. Any help would be appreciated! :)
<!doctype html>
<html>
<head>
<title> JavaScript Playground </title>
<script type="text/javascript">
function grade(Grade){
if (Grade <= 90 && Grade >= 100) {
return alert("You made an A!");
} else {
return alert("I don't know what you made!");
}
}
</script>
</head>
<body>
<script>
var Grade = parseFloat(prompt("Please enter a number: "));</script>
</body>
</html>
Several things
Your value cannot be <=90 AND >= 100
No need to return the alert
You need to call the prompt before the grade or move the prompt to the function
Prompt can return empty string, or something not a number so test if it is a number
Your code could be written
function grade(){
var Grade = prompt("Please enter a number: ");
Grade = isNaN(Grade) || Grade.trim()==="" ? 0 : +Grade; // force number if "Not a Number" or an empty string
if (Grade >= 90 && Grade <= 100) {
alert("You made an A!");
} else {
alert("I don't know what you made!");
}
}
grade()
That said,
You should already use eventListeners
It is nicer to use some element's text content than an alert
I also show you a ternary instead of the if (a) text = "a"; else if (b) text = "b" construct
<!doctype html>
<html>
<head>
<title> JavaScript Playground </title>
<script type="text/javascript">
// helper function to make a number from whatever is entered
const makeNum = str => isNaN(str) || str.trim() === "" ? 0 : +str; // convert to 0 if not a number
function grade(Grade) {
Grade = makeNum(Grade); // convert to number
return Grade >= 90 && Grade <= 100 ? "You made an A!" : "I don't know what you made!";
}
window.addEventListener("load",function() { // on page load
document.getElementById("gradeMe").addEventListener("click",function() {
document.getElementById("res").textContent = grade(document.getElementById('grade').value);
})
});
</script>
</head>
<body>
Please enter a number:
<input type="text" id="grade">
<input type="button" id="gradeMe" value="grade me" />
<span id="res"></span>
</body>
</html>
The line directly after
var Grade = parseFloat(prompt("Please enter a number: "));
You can call your function like grade(Grade);
The if/else is completely unrelated to how you call the function but I think the conditional inside your if statement is mixed up. I'm guessing you probably meant for it to be Grade >= 90 && Grade <= 100 rather than Grade <= 90 && Grade >= 100.

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>

How to validate a number being an integer

Recently I have been working on a "spinner" that increases and decreases a number by 1 each time, however I've wanted to add validation to the program so that integers only are accepted (no decimals) however I've been unsuccessful in doing this.
I've researched the use of NaN and parseValue(s) but I've not found a way of including this to my script, and any help would be highly appreciated. All code in the example given works as I want it to, therefore I only need the validation.
CODE: HTML
<!DOCTYPE html>
<html>
<head>
<h1>Spinners in JavaScript</h1>
</head>
<body>
<p id="textDisplay()">0</p>
<div align="middle">
<button onclick="spinUp()">+1</button>
<button onclick="spinDown()">-1</button>
</div>
</body>
</html>
JavaScript
currentNumber = 0;
function spinUp() {
if(currentNumber==100){
currentNumber = 0;
document.getElementById("textDisplay").innerHTML = currentNumber;
} else if(currentNumber < 100) {
currentNumber++
document.getElementById("textDisplay").innerHTML = currentNumber;
}
}
function spinDown() {
if(currentNumber>0){
currentNumber--;
document.getElementById("textDisplay").innerHTML = currentNumber;
} else if(currentNumber<=0){
window.alert("Too low! Higher!");
currentNumber++;
document.getElementById("textDisplay").innerHTML = currentNumber;
}
}
You could use a method like this:
if (number != Math.round(number)){
alert("Enter a whole number");
}
You can use the === operator as below :
if (data === parseInt(data, 10))
alert("data is integer")
else
alert("data is not an integer")
How to check if a variable is an integer in JavaScript?
v === v | 0;
this is true if v is an integer, false otherwise.

html input field set range

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!!!");
}
}
}
});
});

Categories

Resources