Form Validation with Javascript on a "Dynamic" Form
Here's one for savvy amongst us.
Right now I'm working on a form that is built using a PHP foreach loop. The name s of the form items are dynamic, in that they are qty_$itemid. What i need to do is ensure that what is put into the qty_$itemid field is, indeed, a number. I was hoping to use Javascript instead of another function in PHP. Any tips or suggestions on how I can finish this?
Right now I'm working on a form that is built using a PHP foreach loop. The name s of the form items are dynamic, in that they are qty_$itemid. What i need to do is ensure that what is put into the qty_$itemid field is, indeed, a number. I was hoping to use Javascript instead of another function in PHP. Any tips or suggestions on how I can finish this?
0
Comments
function isNum(argvalue) { argvalue = argvalue.toString(); if (argvalue.length == 0) return false; for (var n = 0; n < argvalue.length; n++) if (argvalue.substring(n, n+1) < "0" || argvalue.substring(n, n+1) > "9") return false; return true; }That's pretty much what I was hoping for, lucky thing for me I found another way to do it by simply running the "eval" function on the string. Here's the code:
function checknumber_qty(idno){ eval("var x=document.orderform.qty_" + idno + ".value") var anum=/(^\d+$)|(^\d+\.\d+$)/ if (anum.test(x)) testresult=true else{ alert("Please input a valid number in the QTY field") testresult=false }The eval() function can be useful and often seems like the best solution, but it is also very very slow compared to every other Javascript function. There are many articles out there urging Javascript developers to fully explore all possible solutions before using it. Keep in mind that Javascript is client-side scripting, so the runtime for you is different than Joe Schmoe on a PII.
Your problem is that the form elements have ID#s in their names and you don't know these numbers?
If you know what # they start and end at, try this:
for(i = startNum; i <= endNum; i++) { tempString = "qty_" + i; if( isNaN(orderform.elements[tempString].value) ) { alert("Please input a valid number in the QTY field"); testresult = false; } }Or, if every input element in that particular form needs to be validated, you could do this:for(i = 0; i < orderform.elements.length; i++) { if( isNaN(orderform.elements[i].value) ) { alert("Please input a valid number in the QTY field"); testresult = false; } }Don't get me wrong. Eval is nice. It works great. It's probably not slow enough for you or most of your site's visitors to notice. But if you have lots of these fields to check, a hundred evals or so could get ugly.I might try your suggestion, just to see if it might work, but I'm not sure how to work it out if I'm not sure what number is tacked on (as I have to take that unique number and apply it to the item to update the information in the database).