I have asp:textbox I want to restrict the text box to allow only integer values.
How can I do that using javascript in asp.net.
If you use the replace function and some regualar expressions you will be able to do this.
<input type="text" name="textbox" onkeyup="integersOnly(this)">
<script type="text/javascript">
function integersOnly(obj) {
obj.value = obj.value.replace(/[^0-9-.]/g,'');
}
</script>
That will also keep in the decimal place.
If you just want integers use:
obj.value = obj.value.replace(/[^0-9]/g,'');
All this function is doing is taking what is input and removing any characters that are not numbers.
Alternatively you can do this in jQuery. If you use jQuery let me know and I will let you know how I do it.
EDIT
Following on from your comment you could use the following updated function:
var integer_only_warned = false;
function integersOnly(obj) {
var value_entered = obj.value;
if (!integer_only_warned) {
if (value_entered.indexOf(".") > -1) {
alert('Please enter an integer only. No decimal places.');
integer_only_warned = true;
obj.value = value_entered.replace(/[^0-9]/g,'');
}
}
obj.value = value_entered.replace(/[^0-9]/g,'');
}
What this is doing is first checking if a decimal has been entered. If it has then it is warning the user and then removing the decimal place. I have also added a check, so that the warning only comes up once every page load.
Hope that helps.
Use a RegularExpressionValidator control and set the EnableClientScript property to True.
Check this example.
Restrict Characters and Allow only Integers in Textbox using JavaScript
Just to throw this in too, if you happen to be using AJAX Control Toolkit, there is an extender already built that makes filtering content a snap: http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/FilteredTextBox/FilteredTextBox.aspx
Related
I built a calculator in ReactJs. And i would like to prevent the user from entering more than one decimal element eg 2..3 Anytime a user does this i'd like to replace all the decimal elements with a single one. So 2..3 would become 2.3
This is how i am trying to achieve this but it doesnt work
if (calc.input.match(/\.{2,}/g)) {
setCalc(calc.input.replace(/\.{2,}/g, "."));
}
setCalc is the hook i'm using to change state.
This should help. It basically keeps the input from happening if we already find a decimal in the string already when hitting a key.
const text = document.querySelector('input[type="text"]');
text.addEventListener('keypress', e => {
// if the text already includes a decimal, and our current key is a decimal, prevent the new key from being added.
if (text.value.includes('.') && e.key == '.') e.preventDefault();
});
<input type="text">
Remembered that strings are immutable and so to change the value of calc.input I would have to reassign it to itself. And so this approach worked for me for this particular use case.
Note that it doesnt prevent input in the form 9.9.9
if (calc.input.match(/\.{2,}/g)) {
setCalc(calc.input = calc.input.replace(/\.{2,}/g, "."));
}
Try this...
var S='456...........876';
S=S.replace(/\.+/g,'.'); // I escape the period with a slash and place the + next to it to mean "all".
document.write(S);
Hopefully I get this format right. I know this is a newbie question and probably pretty obvious but I am confused on how to check these fields. I have two input fields on a JSP file:
<input id="CMDScheduleNumber" type="number" class="textsmall" maxlength="5"
onKeyPress="return numbersonly(this, event)"/>
<input id="CMDContractYear" type="number" class="textsmall" maxlength="4"
onKeyPress="return numbersonly(this, event)"/>
I have a function in a script called "searchEFT" that is checking if either the schedule number or contract year is populated then both must be populated.
<script type="text/javascript">
//function for onchange
$(document).ready(function () {
$("#searchEFT").click(function () {
var Cmd_Sched_Number = document.getElementById("CMDScheduleNumber");
var Cmd_Contract_Year = document.getElementById("CMDContractYear");
var Cmd_Status = document.getElementById("CMDSchedStatus");
var Cmd_Creation_Date = ocument.getElementById("CMDCreationDate");
if (Cmd_Sched_Number == "") {
If(Cmd_Contract_Year !== "")
alert("Schedule Number and EFT Contract Year must be both populated");
return;
}
else if (Cmd_Sched_Number == "") {
alert("Schedule Number and EFT Contract year must be both populated");
return;
}
When I tried to do a debugger if the Cmd_Sched_Number field the value is shown as "" but the valueasnumber is shown as 'NaN'. So when I do a check, should I check it was "" or check it as numeric with isNaN and/or IsNull?
Thanks for the help
var Cmd_Sched_Number = document.getElementById("CMDScheduleNumber");
Gets the Element.
Use .value to get value from the Element
Something like:
var Cmd_Sched_Number = document.getElementById("CMDScheduleNumber").value;
Also, since you have jQuery already, consider using it.
Like:
var Cmd_Sched_Number = $("CMDScheduleNumber").val();
Custom code validations are really a mess. How many conditions you can check? There are a lot of open source libraries and they do the job pretty much well.
I would recommend you to use validate.js. Its very simple and easy to use. It sets the rules on the fields and validate according to them.
Probably you will have to do little more efforts right now to shift your code, but it will be very easy then.
As Aragorn correctly pointed out, make sure you're getting the values, not the Jquery objects or DOM elements.
function isPopulated(val) {
return !(val === '' || isNaN(val));
}
//and then in your click event handler...:
if((isPopulated(Cmd_Sched_Number) || isPopulated(Cmd_Contract_Year)) && !(isPopulated(Cmd_Sched_Number) && isPopulated(Cmd_Contract_Year))) {
//Handle the case where one is populated and the other isn't, assuming you want to treat any non-numbers as not populated.
}
This is if you want a common block for any scenario of one populated and the other not, it will be evaluated like an XOR.
The reason my isPopulated function checks for both an empty string and isNaN is that isNaN('') will evaluated false.
If you don't care whether the entered value is actually numeric or not, then you would maybe want to check value.length > 0, for example.
Please I have my Jquery code that I want to do few things since. I have a form with a bunch of textboxes. I want to validate each textbox to allow numbers only. To also display error where not number.
var validateForm = function(frm){
var isValid = true;
resetError();
$(":text").each(function(variable){
console.log("The variable is" , variable);
if(!isNormalInteger(variable.val))
{
$("#error"+variable.id).text("Please enter an integer value");
isValid = false;
}
});
if(!isValid)
return false;
};
The above fails. When I print the variable on my console I was getting numbers 0 - 9. My textboxes where empty yet, it returns numbers. I tried variable.val() still fails and return numbers. I modified my select to
$("input[type=text]", frm).each();
Where my form is my form selected by id. It also failed. Below is the example of my html label and textbox. I have about ten of them
<div class="grid-grid-8">
<input class=" text" id="id" name="name" type="text">
<br>
<p class="hint">Once this limit is reached, you may no longer deposit.</p>
<p class="errorfield" id="errorMAXCASHBAL"></p>
Please how do I select them properly? Moreover, my reset function above also returns incrementing integers for value. The p property is of class errorField and I want to set the text property. Please how do I achieve this? Previously I tried the class name only $(.errorField). It also failed. Any help would be appreciated.
var resetError = function(){
//reset error to empty
$("p errorfield").each(function(value){
console.log("the val", value);
//value.text() = '';
});
};
//filter non integer/numbers
function isNormalInteger(str) {
return /^\+?\d+$/.test(str);
}
The main problem is your selectors in javascript. And as laszlokiss88 stated wrong usage of .each() function.
Here is a working example of your code: jsFiddle in this example all .each() functions use $(this) selector inside instead of index and value
You are using .each wrong because the first parameter is the index and the second is the element. Check the documentation.
Moreover, the correct selector for the resetError is: p.errorfield
So, you should modify your code to look something like this:
var resetError = function(){
$("p.errorfield").each(function (idx, element) {
$(element).text("");
});
};
With this, I believe you can fix the upper function as well. ;)
EDIT:
Ok so I'm updating this question, to show what I've built as I've still not been able to fix this issue. Here is an image of what I've got. So as you can see,
When the user enters a value, the calculation (they are just percentage and total calculations are done "onkeyup". As you can see because of this they return "NaN". Is there a way for me to stop the field displaying a NaN and then subsequently only showing the total values?
I have thought about this and I could just get all the fields to calculate as soon as something is input into the final field? What do you think. Apologies to all those that had perviously answered my question, I am still trying to figure out the best approach, I'm just not as good with JavaScript as I am with HTML/CSS!!
You should try writing a checkNumber function that takes the entered value as its argument (rather than referring directly to each field inside the function). Something like this:
var checkNumber = function (testval) {
if ( isNaN(testval) ) {
alert('Bad!');
// clean up field? highlight in red? etc.
} else {
// call your calculation function
}
}
Then bind that function to the keyup event of each form field. There are a number of ways to do this. Look into addEventListener(), or the binding features of a framework like jQuery (.delegate() or .keyup(), e.g.).
Note that if you do bind the function to the event, you won't have to explicitly pass in the value argument. You should be able to work with a field's value within the function via this.value. So you'd have something like this:
var checkNumber = function () {
if ( isNaN( this.value ) ) {
alert('Bad!');
// clean up field? highlight in red? etc.
} else {
// call your calculation function
}
}
And then (with a naive binding approach by ID):
document.getElementById('id_of_a_field').addEventListener('keyup', checkNumber, true);
Can't you just initialize the text box with a default value, say 0?
Why don't you use 3 different functions or an argument to identify which of the inputs the user is pressing? If each of the inputs calls checkNumber(1), checkNumber(2) and checkNumber(3) you can only validate the input that the user is using instead of validating all 3 at the same time.
Alternatively you can use input validation and instead of an alert just return false to prevent the user from inputing invalid chars
How about use short-circuit evaluation with jsFiddle example
EDIT for parseFloat:
function checkNumber()
{
var sInput = parseFloat(document.getElementById('sInput').value || 0);
var dInput = parseFloat(document.getElementById('dInput').value || 0);
var pInput = parseFloat(document.getElementById('pInput').value || 0);
if (isNaN(sInput) || isNaN(dInput) || isNaN(pInput)) {
alert("You entered an invalid character. Please press 'Reset' and enter a number.");
}
}
So if pInput is undefined just use 0, but if the input has value then use that value.
SIDE NOTE: white space is actually a number, +' '; // 0
i need to control the numbers of characters in an input field using jquery ...
ive got some control already but, i dont know what else to do ....
var foo = function(){
if($('#foo1').val() == ''){
$('.foo_foo_c').load('../html/message_error_number.html');
}else{
$('.foo_foo_c').load('../html/foo_foo.html',function(){
listaStyle();
listaPagadasStyle();
listaDetalleLlamadasStyle();
});
}
};
Look at using the jQuery validation plugin and set up maxLength or rangeLength rule in addition to requiring that it be a number.
I think you want something like the Alphanumeric plugin.