Javascript Validation for Positive Integer Only Input - javascript

I have two text boxes, in it will only be allowed positive integers.
If any alphabetical values or any other characters (e.g. %$&*£") are entered, an error message should be displayed and the values must not render a table.
<input type="button" value="total" name="B3" onclick="powerOf();">
This line allows for calculation to be made, how can this validation stop this from happening
when the incorrect values are entered?? As of now minus numbers are calculated and entering alphabets produces an empty table which is not quite what I was going for:
(no1== no1.match(/^-\d+$/) ? alert("First number must be positive"): no1 = no1 ? no1 : 0);
(no2== no2.match(/^-\d+$/) ? alert("Second number must be positive"): no2 = no2 ? no2 : 0)
var range1 = parseInt(no1);
var range2 = parseInt(no2);
Any ideas?

Note: you can do this simply via HTML5 form validation:
<input type="number" min="1">
Then you won't be able to submit the form unless the entered value is a number higher than 1. This only seems to work in Chrome though.
To answer your question, what you're looking for is event.preventDefault(). If you change your onclick function to:
<input type="button" value="total" name="B3" onclick="powerOf(event);">
then you can run event.preventDefault() in the powerOf function, and when you run that, the event will be "cancelled". For example:
function powerOf(event) {
if (!/^\d+$/.test(document.getElementById('input-1').value)) {
event.preventDefault();
}
}
that will cancel the click event when the value of the input with id="input-1" is not digits only.
See this demo for a working example.

Related

Dynamically check value and display alarm popover

I want to validate user input so he only provides numbers from a certain range with 0,5 steps. But I want my website to do it every time user swaps to another input form, not after he sends the data to my view. Can you give a hint of how should it be done? I don't know Javascript but I know there is onfocusout DOM event. Is it correct approach to use it, check whether or not value is valid and display an alarm based on that?
In general, there's no problem using onfocusevent.
Here's a hint on how to do this:
Create the input field
Add the onfocusout event handler and assign it a JavaScript function
Define the JavaScript function responsible for the validation process (which is, the same function we talked about in step 2)
This function takes the value inside the field and compares it, if it's not inside the range you desire then you can show an alarm or something like this.
I made a demo that doesn't involve alarming the user but instead it colors the border with either green or red, when you get desperate pay it a visit:
<input type="number" id="field1" onfocusout="validateField(0, 100, 'field1')"/><br/><br/>
<input type="number" id="field2" onfocusout="validateField(200, 300, 'field2')"/><br/><br/>
<input type="number" id="field3" onfocusout="validateField(400, 500, 'field3')"/><br/><br/>
<script>
function validateField(min, max, id) {
const value = document.getElementById(id).value;
if (value < min || value > max) {
document.getElementById(id).style.borderColor = "red";
}
else {
document.getElementById(id).style.borderColor = "lime";
}
}
</script>

How to limit a dot string to only one character even when holding down a non-number key

I'm creating a input validation to allow only a numeric and dot input.
It does limit the dot character to one onkeypress but when holding down a non-number key it's not.
<input class="form-control" type="text" onkeyup="this.value=this.value.replace(/[^0-9.{1}$]/g, '').replace(/(\..*)\./g, '$1');" />
How can i limit the dot string to one even when holding down a non-number key?
You shouldn't need javascript here: use input with type number (see MDN). If the typed user input is invalid (it may contain more dots), the input has no value (check it with the button of the snippet). For example:
document.querySelector("button").addEventListener(
"click",
() => {
const val = document.querySelector("input").value;
console.log( val || "Invalid");
}
);
<input type="number" step="0.1" min="1" max="20" value="1.0">
<button>show value</button>
You can use
^(?=^[^.]*\.?[^.]*$).+$
<form>
<input type='text' pattern='^(?=^[^.]*\.?[^.]*$).+$'/>
<button typ='submit'>submit</button>
</form>
Note:- If you need one . to be must you can change above regex to
^(?=^[^.]*\.[^.]*$).+$
You could use <input type="number" /> or <input pattern="[0-9]*\.?[0-9] /> as the others have suggested.
However,
If you want to do it "manually"
You could use the onkeypress attribute. This is the event which fires for every repetition of a character. After firing this event, the browser updates the input value.
Canceling the event
If we return a false like such: onkeypress="return false", you will notice that the input value won't update anymore, no matter what key you press. We can even add a condition: onkeypress="if(event.key != '0') return false;". In this case, you will only be able to write 0s in the input.
So, this is the event during which we will have to check, and make up our mind if we are going to allow the newly pressed key to have an effect. We will return true or false accordingly. However, there is only one little problem.
Composing the new value
Before we are going to decide if we allow the newly pressed key to have an effect, we need to see what effect it would have. We need to see how the input value will look like after this event. So we are going to compute it. Right now, the input still contains the current (without the new character) value.
Implementation
The JavaScript function:
function checkNumber(input, event){
//- We have the old value in input, and the currently pressed key in event.key
//- So we have the compute the new to be value of the input, to check if it's correct
//- To do this, we break the text into an array of characters, and insert the key
//- at the cursor's position - Check on MDN what Array.prototype.splice() does
var newValue = input.value.split('');
newValue.splice(this.selectionStart, this.selectionEnd-this.selectionStart, event.key);
newValue = newValue.join(''); //- Put it back into string form
return /^[0-9]*\.?[0-9]*$/.test(newValue);
}
And to use it:
<input class="form-control" type="text" onkeypress="return checkNumber(this, event);" />

jQuery replace with regex not working correctly

I want to exclude all characters which are not a digit or minus.
What strikes me is that I cannot start with a minus or enter it anywhere. Only after digits and using the keyboard arrow button is entering a minus possible.
What I would like is being able to just enter -60 or something the like.
What should I change?
$('.minus').keyup(function() {
var txt = $(this).val();
var nwtxt = txt.replace(/[^\d-]/ig, "");
$(this).val(nwtxt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" maxlength="9" class="tekstvakjes minus">
Instead of using input type number use text
I think it's some kind of browser defence meganism that whenever you insert something that is not a number inside a number input field and you request the value from it, it will simply be null/undefined. On type="text" it looks like this is fine.
Also note your cursor is always put at the end of the text, because you replace the text always. So you can't insert a - (dash) before a number with only keyboard interaction. and a dash anywhere but in front of a number is invalid!
You can try to type in -60 in the number field as well but you first need to insert. 60 and then the minus character.
also its better to use $('.minus').input( instead of keyUp, since you can use the mouse to insert values as well (and the scroll wheel).
$('.minus').keyup(function() {
var txt = $(this).val();
console.log("value i got:",txt); //i added this logging to see that you didn't get anything on number.
var nwtxt = txt.replace(/[^\d-]/ig, "");
if(nwtext !==txt) //add this if statement so your cursor does not constantly jump to the end!
$(this).val(nwtxt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" maxlength="9" class="tekstvakjes minus" placeholder="number">
<input type="text" maxlength="9" class="tekstvakjes minus" placeholder="text">

Variable Naming Grammar HTML/ JavaScript

How do I properly send values from two HTML input fields
into a JavaScript function, which displays a value into
a third final HTML input field?
What do I have to change to get this to work?
I am sure it is the function names and variable values
not getting sent to the function.
I have this input field we'll call input 0(dbel):
<input type="number" id="dbel" value="1" step="0.1" min="0">
I have this field input 2(npml) here:
<input id="npml" onkeyup="convert1('NPML')" onchange="ln5cmpower('npml')">
This is the function which determines input 3 rounded to the nearest hundredth;
input3 = ((1/.05) + (1/ -(input2 - (input0/100))))
function ln5cmpower(npml, dbel) {
powerln5cm = ((1/.05)+(1/-(document.getElementById("npml").value-(document.getElementById("dbel").value/100))));
document.getElementById("POWERln5cm").value = Math.round(powerln5cm*100)/100;
}
And here is input 3, which will display final results that don't go anywhere else.
<input id="POWERln5cm">
Input 2 already may determine, and may be determined by, input 1,
which is what function convert1 is for.
Function convert1 works fine so I suppose I may ignore it.
The part that doesn't work is function ln5cmpower, from what I can tell.
Once a value shows up in input 2(npml),
this field will trigger function ln5cmpower to
determine the value of input 3(POWERln5cm) using the value of
input 2(npml) and input 0(dbel) once a value shows up in input 2(npml).
Your code is working fine, I assembled your code to make a working demo. Although the function you called on keyup event onkeyup="convert1('NPML')" is missing that throws an exception when entering values to input fields preventing the output of your onchange event.
function ln5cmpower(npml, dbel) {
powerln5cm = ((1/.05)+(1/-(document.getElementById("npml").value-(document.getElementById("dbel").value/100))));
document.getElementById("POWERln5cm").value = Math.round(powerln5cm*100)/100;
}
<input type="number" id="dbel" value="1" step="0.1" min="0">
<input id="npml" onchange="ln5cmpower('npml')">
<input id="POWERln5cm">

getting not a number(NaN) error html/js

I am getting NaN error while clicking radio button first. The page have a3 radio button when I click that 1st button it saya NaN and remaining 2 buttons has no response
this is my HTML
<input type="hidden" name="totalamount" id="totalamount" value="<?php echo get_total_amount();?>" /
<input type="radio" name="rmr" id="payment1" value="3" onclick="updatepayment(this.value)" />
<input type="radio" name="rmr" id="payment2" value="5.5" onclick="updatepayment(this.value)" />
<input type="radio" name="rmr" id="payment4" value="10" onclick="updatepayment(this.value)" />
<div id="finalamount">
</div>
also I have mentioned my JS
$(document).ready(function(){
$('input[name=rmr]').click(function () {
//make sure one is checked
if($('input[name=rmr]:checked').length > 0) {
$('#finalamount').html($("#totalamount").val() * $("input[name=rmr]:checked").val());
}
});
});
Three things:
1) As you're using the amount from the "totalamount" element, one has to ask: Are you sure that
value="<?php echo get_total_amount();?>"
...is outputting a valid number? Because if not, then the code
$('#finalamount').html($("#totalamount").val() * $("input[name=rmr]:checked").val());
...will indeed result in NaN. The * operator will try to convert both of its operands from strings to numbers, and of course if the value output by that PHP code isn't a valid number (for instance, if it's "$0.00" or something), the result of the conversion will be NaN. And NaN times anything is NaN.
This example of an invalid amount in the "totalamount" element yields something that looks a lot like the behavior you describe. (That code isn't identical to yours, I did some very light refactoring, see below. But for the purposes of demoing an invalid number, it doesn't matter.)
2) There's no > at the end of that hidden input in the text of your question. If you did a direct copy-and-paste, I wonder if that could be the problem?
3) As you're using jQuery, there's no need for the onclick attributes. Instead:
$(document).ready(function(){
$("input[name=rmr]").click(function(){
var checked = $("input[name=rmr]:checked");
updatePayment(this.value);
if (checked.length > 0) { // make sure one is checked
{
$("#finalamount").html( $("#totalamount").val() * checked.val() );
}
});
});
...assuming you want updatePayment called every time.
Live example
Folding updatePayment into the main click behavior lets you avoid any issues that may exist with the order in which DOM0 (onclick attribute) handlers and DOM2 handlers (the ones used with jQuery) are called.
It is working fine for me. Please find the working code in jsfiddle. You have to make sure that the value in the totalamount input is a numeric value. You can user parseFloat() to convert the string value into a float value.
Ex
parseFloat($("#totalamount").val()) * $("input[name=rmr]:checked").val()
As #Crowder parseFloat() is not necessary since javascript take care of the type conversions.
You try to put an alert()/console.log() command before the calculation to see whether the totalAmount is having an non-numeric value. Ex: alert($("#totalamount").val())

Categories