I am checking numeric value for one textbox like this:
function validateNumeric() {
var old = document.getElementById("tbNum").value;
var new = old_val.replace(/^\s+|\s+$/g,"");
var validChars = '0123456789';
for(var i = 0; i < new.length; i++){
if(validChars.indexOf(new.charAt(i)) == -1){
alert('Please enter valid number');
return false;
}
}
document.getElementById("tbNum").value = new;
return true;
}
I want to use the same function and check numeric value for other text boxes that requires numeric value. How can I pass value of tbID, tbDiscID, as well as above and return true before submitting the form.
I am not sure what you mean by tbId and tbDiscID, but to do this in plain JavaScript, you can generalize this solution by traversing JavaScript's arguments object, which lets you pass in any variable number of arguments to your function. This will help you take in the IDs you need. Your new solution would look something like the following:
function validateNumeric() {
for (var arg in arguments) {
var id = arguments[arg];
var old = document.getElementById(id).value;
var new = old_val.replace(/^\s+|\s+$/g,"");
var validChars = '0123456789';
for(var i = 0; i < new.length; i++){
if(validChars.indexOf(new.charAt(i)) == -1){
alert('Please enter valid number');
return false;
}
}
document.getElementById(id).value = new;
return true;
}
}
Then invoke it like:
validateNumeric("myTextbox1", "myTextbox2", ..., "myTextboxN");
Where myTextBox1 ... myTextBoxN are the IDs of your textboxes.
use parameter for the function, for using it on different elements
validateNumeric(value) {
use the onsubmit parameter on the form tag to call a validation
<form name="myForm" action="dosomething.php" onsubmit="return validateForm()"
write your validate function with calls for all elements
function validateForm() {
if (!validateNumeric(document.getElementById("tbNum"))) {
return false;
}
...
return true;
would be one way..
edit
forgot the check within the validateForm method
Related
So I've tried making a function that loops through the elements of a form and checks the length of the elements, and if so, change the class so they can be styled differently. The code I have I assumed would work, and I'm not getting any errors in my console, so I can't pinpoint what is going wrong exactly. If someone could tell me why this won't work or how to fix it that would be awesome! Thankyou!
function validate_form(){
var form = document.forms['form_name']; //store form into a variable
var validated = true; // store return value for onsubmit attribute
for(i=0; i<form.elements.length; i++){
if(form.elements[i].value.length){ // check if form elements are empty
form.elements[i].className = "validate_failed"; // if elements are empty, add a class that will style them
validated = false;
return validated;
} else{
validated = true;
return validated;
}
return validated;
}
return validated;
}
Try
function validate_form(){
var form = document.forms['form_name']; //store form into a variable
for(var i=0; i<form.elements.length; i++){
if(form.elements[i].value.length===0){ // check if form elements are empty
form.elements[i].className = "validate_failed"; // if elements are empty, add a class that will style them
return false;
}
return true;
}
assuming
<form onsubmit="return validate_form()" ...
or make it all unobtrusive
window.onload=function() {
document.forms['form_name'].onsubmit=function() {
for(var i=0; i<this.elements.length; i++){
this.elements[i].className = "";
if(this.elements[i].value.length===0){ // check if form elements are empty
this.elements[i].className = "validate_failed"; // if elements are empty, add a class that will style them
return false;
}
return true;
}
}
}
Because your are returning validated during the first run through of the loop, you'll only ever check the first element of the form. You'll just want to set validated, and return it after the loop (or return when you first set it to false, depending on what you want to do).
Also, like Joe commented, you should have var i instead of just i so that i is not global.
Following code will work for empty element
if(!form.elements[i].value.length){
OR
if(form.elements[i].value.length === 0){
I want to call two functions and if the first returns true then continue to the second, and if it returns false then show an error. This would be defined in one onclientclick.
If only one function is to be called after I clicked the button, the function works.
However, if I combine and write it like this:
TestCheckBox() and TestCheckBox2() are same function, I just need it to validate two gridviews
<script type="text/javascript">
var TargetBaseControl = null;
window.onload = function () {
try {
//get target base control.
TargetBaseControl =
document.getElementById('<%= this.GridView1.ClientID %>');
}
catch (err) {
TargetBaseControl = null;
}
}
function TestCheckBox() {
if (TargetBaseControl == null) return false;
//get target child control.
var TargetChildControl = "chkRow";
//get all the control of the type INPUT in the base control.
var Inputs = TargetBaseControl.getElementsByTagName("input");
for (var n = 0; n < Inputs.length; ++n)
if (Inputs[n].type == 'checkbox' &&
Inputs[n].id.indexOf(TargetChildControl, 0) >= 0 &&
Inputs[n].checked)
return true;
alert('Select at least one checkbox!');
return false;
}
</script>
The problem is when TestCheckBox() returns true, TestCheckBox2() does not work, in this case it does not validate the checkboxes.
How do I make it work perfectly?
Try this:
<asp:.... OnClientClick = "return (TestCheckBox() && TestCheckBox2());" ...
Trying to learn JavaScript, makin decent progress I guess, but I'm stuck at validating a form, tried to see if anybody has the same problem, search didn't turn anything up. So would you please help me?
var minlength = 6;
var pwlength = document.getElementById('psswrd');
var invalid = " ";
function validate() {
if (pwlength.length < minlength && pwlength == invalid) {
alert("Password not valid");
else {
alert("Password okay!");
}
}
submitbtn.onClick = validate();
It is not obvious where you call this - I have wrapped it in a window.onload
you do not access the button correctly. Either of
document.forms[0].submitbtn
document.getElementById("submitbtn") or
document.getElementsByName("submitbtn")[0] will work depending on how you name or ID the button HOWEVER do not assign onclick handlers to submit buttons, instead assign submit handler to the form
there is no point of testing for a single space since that is less than 6 chars anyway.
&& is AND, you mean || OR
onclick must be all lowercase.
You assign the onclick to the result of validate instead of validate
You do not stop the submission
I have taken the trim from here
and I assume the form has ID="form1"
window.onload=function()
document.getElementById("form1").onsubmit = validate;
}
if(typeof String.prototype.trim !== 'function') { // let's help older IEs
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
function validate() {
var minlength = 6;
var pw = document.getElementById('psswrd');
if (pw.value.length < minlength || pw.value.trim() == "") {
alert("Password not valid");
pw.focus();
return false;
}
return true; // allow submission
}
var minlength = 6;
var pwlength = document.getElementById('psswrd');
var invalid = " ";
function validate() {
if (pwlength.length < minlength && pwlength == invalid) {
alert("Password not valid");
}
else {
alert("Password okay!");
}
}
You have a few problems here.
1) pwlength.length won't get you very far. pwlength is equal to an html object, not the value of an html object. Change the actual variable to the following and you should get the correct results:
var pwlength = document.getElementById('psswrd').value;
2) Before the else part of your if ... else statement, you need to end the if statement by closing it with a curly bracket (}). Change that part to the following:
} else {
3) Your validation to check and see if the length == invalid is odd. Double check that and get rid of it.
4) Your onclick event needs to look something like this:
submitbtn.onclick = function(){ validate() };
Notice: lowercase event keyword and function() { ... }; wrapped around the function you want to run.
I am trying to intercept form submits from webpages I dont control.
My current implementation is ...
// During onLoad, loop through all forms and for each form object
var prevonsubmit = formobj.onsubmit;
if (prevonsubmit) {
formobj.onsubmit = function f() {
if(prevonsubmit()) {
interceptform();
return true;
}
return false;
};
} else {
formobj.onsubmit = function ff() {
interceptform();
return true;
};
}
The problem with this is, inside interceptform(), I am unable to identify which form actually made this submission. Is there a way I actually get the form object that is trying to submit? Keep in mind that some of the forms I see do not have a name or id specified and there is more than one form (in the same webpage) with same action.
Edit:
The purpose is capture the content in the input tags that belong to the form.
A made up example of what I see in a form:
<form action="https://duckduckgo.com/html/" method="GET">
<input type="text" name="q"/>
</form>
<form action="https://duckduckgo.com/html/" method="GET">
<input type="text" name="l"/>
</form>
<form action="https://duckduckgo.com/html/" method="GET">
<input type="text" name="l"/>
<input type="text" name="q"/>
</form>
Edit2:
Based on #ruakh answer, the solution I ended up using:
var prevonsubmit = formobj.onsubmit;
if (prevonsubmit)
formobj.onsubmit = createOnSubmitFunctionWithOld(prevonsubmit, formobj);
else
formobj.onsubmit = createOnSubmitFunction(formobj);
// Definition of the functions:
function createOnSubmitFunctionWithOld(prevonsubmit,formObj) {
return function () {
if (prevonsubmit()) {
interceptform(formObj);
return true;
}
return false;
};
}
function createOnSubmitFunction(formObj) {
return function () {
interceptform(formObj);
return true;
};
}
You can simply pass formobj as an argument to interceptform():
interceptform(formobj);
But bear in mind that both with formobj and with prevonsubmit, you have to be careful to avoid capturing a variable you don't want to. For example, in JavaScript, this:
var functions = [];
for(var i = 0; i < 10; ++i)
{ functions[i] = function() { return i; }; }
creates ten functions that all return 10, because they all capture the same i variable that's been incremented up to 10 by the time the functions are ever called. In the above example, you could write something like:
function new_constant_function(return_value)
{ return function() { return return_value; }; }
// ...
var functions = [];
for(var i = 0; i < 10; ++i)
{ functions[i] = new_constant_function(i); }
to copy each value of i into a new local variable return_value whose value never changes; or, a bit more tersely, this:
var functions = [];
for(var i = 0; i < 10; ++i)
{ functions[i] = (function(_i){ return function(){ return _i; } })(i); }
You'll almost certainly need to do something similar in your case. (But without seeing a bit more of the context of your code, it's hard to say exactly what.)
Why not loop through document.forms and append a hidden field to each one, or assign an id to the form itself.
If you are loopoing over the forms from a function, then:
> var prevonsubmit = formobj.onsubmit;
> if (prevonsubmit) {
> formobj.onsubmit = function f() {
> if(prevonsubmit()) {
prevonsubmit has a closure to the outer variable, it will reference the last value of prevonsubmit, so they will all reference the same function. This may "work", but will fail if any of your forms has a current listener that is different to any other form.
> interceptform();
You can simply pass this from the function to interceptform:
interceptform(this);
and interceptform will be passed a reference to the element calling the function (presumably the form being submitted).
> return true;
> }
> return false;
That will (probably) cancel submission of any form that doesn't have an existing listener. Is that what you want?
> };
> } else {
> formobj.onsubmit = function ff() {
Named function expressions are known to be buggy in at least one widely used browser. If you don't need a name (and it doesn't seem to be used here for anything), dont' use one. Keep the function anonymous.
> interceptform();
> return true;
> };
> }
I have an assignment in which I need to make two arrays (NAME and SALES). I need to populate the array of up to 100 components. Then, I need to calculate gross pay using a calcPay() function. I am having trouble figuring out how to get the function to work, it either prints the resulting table with the Pay column as 'undeclared', or it just stops working when it comes to that spot, no matter how many NAMES and SALES are entered into the array. I have this in the body script:
var i=0;
var NAME = new Array();
var SALES = new Array();
do
{
NAME[i]=getName();
SALES[i]=getSales();
i++;
var again=confirm("Would you like to enter another salesperson's stats?");
}while(again && i<=100);
var i=0;
for (var i=0;i<NAME.length;i++)
{
printRow();
}
And this is the header:
function getName()
{
do
{
var name=prompt("What is the salesperson's full name?");
}while (name==""||name==null);
return name;
}
function getSales()
{
do
{
var sales=prompt("Please enter salesperson's sales.");
}while(sales==""||isNaN(sales));
return parseFloat(sales);
}
calcPay(sales)
{
var pay=sales*.1+1000;
return pay;
}
function printRow()
{
document.write("<tr>");
document.write("<td>"+NAME[i]+"</td>");
document.write("<td>"+SALES[i]+"</td>");
var payment=calcPay(SALES[i]);
document.write("<td>"+payment+"</td>");
document.write("</tr>");
}
This is not the full extent of the assignment by any means, I just want to make sure that I have a handle on the feeding and manipulating of the arrays (which I don't, obviously).
Thanks for any tips.
Generally - your code works, find it here:
http://jsfiddle.net/osher/GhZSf/
However -
there is a missing "function" before calcPay
calcPay(sales)
{
var pay=sales*.1+1000;
return pay;
}
should be
function calcPay(sales)
{
var pay=sales*.1+1000;
return pay;
}
that's all
name and sales are out of scope this function will not do what you think it will and even if it does it is wrong.
Use an if statement .
function getName()
{
do
{
var name=prompt("What is the salesperson's full name?");
}while (name==""||name==null);
return name;
}
function getSales()
{
do
{
var sales=prompt("Please enter salesperson's sales.");
}while(sales==""||isNaN(sales));
return parseFloat(sales);
}