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. ;)
Related
This has me stumped, and should be pretty simple.
I have an input in my html:
<input type="text" id="fafsaNbrFam" name="fafsaNbrFam" value="<%=nbrFam%>" class="hidden" />
System.out.println(nbrFam); // Works, gives me "6"
Then my js code:
$("#submit").click(function(e) {
var numEntries = 0;
var fafsaNbr = 0;
$("input[name^='name_']").each(function() {
if (this.value) {
numEntries++;
}
});
// EVERYTHING ABOVE HERE WORKS
fafsaNbr = $("input[name=fafsaNbrFam]").val();
alert(fafsaNbr + "X");
// WHERE THE 6 is I want to put the variable fafsaNbr, just hardcoded for now.
if (6 > numEntries && !confirm("The number of members you listed in your household is less than the number you indicated on your FAFSA. Please confirm or correct your household size. ")) {
e.preventDefault();
}
});
On my alert to test this, I get "undefinedX", so basically my jquery to get the value is coming up undefined.
EDIT: So it turns out my code wasn't the problem, but the placement of my input. Even though the original input placement was being processed, once I changed it, it all worked properly. Needless to say, I am still stumped.
You are missing the quotes around the name value. Try:
fafsaNbr = $("input[name='fafsaNbrFam']").val();
Your code is working fine,
I just added your code to jsFiddle and it works
Live EXAMPLE
Could you please make sure, the java scriplet is loading inside the value tag properly or not by checking the view source in browser?
Try to parse the value of the input like this:
fafsaNbr = parseInt($("input[name=fafsaNbrFam]").val());
Or Check whether the $("input[name=fafsaNbrFam]") is undefined or not.
My problem is, I want to retrieve checkbox id at runtime and use them later for other purpose.
But retrieved id is read as object.
My Code is:
// Following code gives id of checkbox which contains myCheckbox as its id.
var myCheckbox= $('input[id$=myCheckbox]')[0].id;
// and Now I want to check if that checkbox is checked with following code:
if ($(myCheckbox).is(':checked'))
return 1;
else
return 0;
But here myCheckbox id is read as Object instead of id and thus always enter in else condition and returns 0. This code works when I enter id of checkbox directly.
if ($('#ctl001_myCheckbox').is(':checked'))
return 1;
else
return 0;
It shouldnot be so complicated, I have been working with Javascript but new to JQuery.
You are getting the ID correctly, but the jQuery selector requires the # symbol, much in the same way as a CSS selector does. You need to add the # character to your selector:
if ($('#'+myCheckbox).is(':checked'))
return 1;
else
return 0;
BenM is correct, but why are you getting the ID of the element, and then look it up again? You already found the element, there is no need to search for it a second time.
Just keep a reference to the element:
var myCheckbox = $('input[id$=myCheckbox]').first();
// or var myCheckbox = $('input[id$=myCheckbox]')[0];
// and later
if (myCheckbox.is(':checked')) {
// or if (myCheckbox.checked) {
Simply:
return (($('#' + myCheckbox).is(':checked')) ^ false);
Have you tried using:
var myCheckbox= $('input[id$=myCheckbox]').attr('id');
Got a question for you javascript gurus out there. I'm creating a sidebar tool that is comprised of a few different text input fields. The purpose of this tool is to edit copy on a template. I've tried to pass the data entered into the field onchange, but I'm running into problems dumping the data into my js object. This is somewhat what I have in mind:
$('myInputField').(function(){
$(this).onChange(){
// write to variable X
}
});
Essentially I want to have what I'm typing in the input be mimicked live and then I can parse the changes to my database.
$('#myInputField').(function(){
$(this).onkeyup(){
x = this.value;
}
});
or more succinctly:
$('#myInputField').onkeyup(){
x = this.value;
});
You're just looking for the value that's in myInputField within that event handler? Something like this?:
$('myInputField').(function(){
$(this).onChange(){
x = $(this).val();
}
});
I don't remember off the top of my head if this is already a jQuery object. If it is, then this should work and perhaps skip a little bit of overhead:
x = this.val();
Additionally, you can explicitly reference the field with a normal jQuery selector if this is ever overridden with a different context, or if you want to reference other fields as well, etc.:
x = $('myInputField').val();
The problem is, on IE, the onchange event doesn't work on INPUT elements. Thus, you have to use the onkeypress or the onblur event depending on what you want to do.
JS way:
document.getElementById('myInputField').onblur = function() {
var x = this.value
}
jQuery way:
$('#myInputField').blur(function() {
var x = this.value
})
Wouldn't a simply keyup event on the input fields be sufficient?
jQuery:
$('textarea').keyup(function() {
$('#foo').html($(this).val());
});
HTML:
<textarea></textarea>
<div id="foo"></div>
jsFiddle example.
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 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