var test2Regex = /^[0-9]*$/;
The above allows the input to be only numbers and no blanks
var i=0;
var pro = [];
for(var i = 0; i < 2; i++) {
pro[i] = document.getElementById('pro' + i);
if(!pro[i].value.match(test2Regex)){
//alert("You entered: " + pro[i].value)
inlineMsg('pro' + i,'Invalid Input',10);
return false;
}
}
is using the match query the right way to do this as it does work
on single variable not using the getelement id i.e
var phoneno = form.phoneno.value;
if(!phoneno.match(test1Regex)) {
inlineMsg('phoneno','You have entered an invalid Char.',10);
return false;
}
the get element is the only difference but I need that in for it to pass the variable.
Use regex.test method
if(!test2Regex.test(pro[i].value)){
//invalid input, blah-blah-blah
}
Related
I'm developing a small calculator that allows you to input a string. So it has to recognize which sign has to be executed in first place.
My problem is that somewhere and by some reason it creates a stackoverflow. I was expecting if you could help me to find out.
The first for is to give each operator a precedence, so * is more important than +. Second loop is destinated to find the sign into the string, so if input.indexOf(signos[i]) is lower or than 0 it jumps off the operator. if its dalse it goes in and put the number in left side and right side into two aux values and in the end it solves the sign and replace it into the string so at the end it shows you the result.
Thanks.
var input;
var signos = ['*', '/', '+', '-'];
var cursor = 0;
var aux1 = "";
var aux2 = "";
var auxSigno = "";
var resuelto = 0;
var encontrado = false;
function lectura(){
input = document.getElementById("ans").value;
console.log(input);
for(i = 0; i < signos.length; i++){
cursor = input.indexOf(signos[i]);
//console.log(cursor);
if (cursor > -1){
auxSigno = input.charAt(cursor);
//console.log(auxSigno);
for(j = 0; j < input.length; i++){
for(k = cursor-1; comparar(k); k--){
aux1+=input[k];
}
for(l = cursor+1; comparar(l); l++){
aux2+=input[l];
}
operar();
var cadena = aux1+auxSigno+aux2;
var auxCadena = input.replace(cadena, resuelto);
input = auxCadena;
}
}
}
console.log(input);
}
function comparar(caracter){
for(m = 0; m < signos.length; m++){
if (caracter === signos[m]){
return true;
}
}
return false;
}
function operar(){
console.log(auxSigno);
console.log(aux1);
console.log(aux2);
if (signos.indexOf(auxSigno) == 0){
resuelto = parseFloat(aux1) * parseFloat(aux2);
console.log(resuelto + " opc1");
} else if (signos.indexOf(auxSigno) == 1) {
resuelto = parseFloat(aux1) / parseFloat(aux2);
console.log(resuelto + " opc2");
} else if (signos.indexOf(auxSigno) == 2) {
resuelto = parseFloat(aux1) + parseFloat(aux2);
console.log(resuelto + " opc3")
} else if (signos.indexOf(auxSigno) == 3){
resuelto = parseFloat(aux1) - parseFloat(aux2);
console.log(resuelto + " opc4")
} else {
console.log("opc no implementada");
}
}
if the input is "6+6*8", the result should be "54", but it doesn't show anything, just keep doing the for.
I keep getting this error due to these two lines:
document.getElementById('button').innerHTML = '<p><button
onClick = "MultiAnswer('+ questions[output] + ',' + answer[output]
+');">Submit</button></p>';
And I can't figure out what I am missing .
Edit: Here is the surrounding code (Excuse the mess) Contains methods that uses a switch statement to determine the input for the arrays required, from there puts it into the parameters for DisplayQuestion which then passes it to the functions below from the behaviour wanted:
function MultiQuest(questions, choices, answer){
var output = Math.floor(Math.random() * (questions.length));
var choicesOut = [];
document.getElementById('question').innerHTML = '<p id = "Q1">' + questions[output] + '<p><br>';
for(var k = 0;k < choices[output].length; k++ ){
choicesOut.push('<p><input id = "choice'+[k]+'" type = "radio" name = "option" value="'+choices[output][k]+'">' + choices[output][k] + '<p>');
}
document.getElementById('answers').innerHTML = choicesOut.join("");
document.getElementById('button').innerHTML = '<p><button onClick = "MultiAnswer('+ questions[output] + ',' + answer[output] +');">Submit</button></p>';
document.getElementById('score').innerHTML = '<p>' + score + '<p>';
}
function MultiAnswer(questions, answer, pageType){
var currentQuestion = document.getElementById('Q1').textContent;
var number = multiQuestions(currentQuestion, questions);
var correctAnswer = answer[number];
var givenAnswer;
var options = document.getElementsByName('option');
var i
for(i = 0; i < options.length; i++){
if(options[i].checked){
givenAnswer = options[i].value;
}
}
if(givenAnswer == correctAnswer){
alert("Right Answer!");
score++;
} else {
alert("Wrong Answer!");
score = 0;
}
i = 0;
DisplayQuestion(pageType);
}
function multiQuestions(currentQuestion, whichArray){
for(var i = 0; i < multiquestions.length; i++){
if(currentQuestion == whichArray[i]){
return i;
}
}
return null;
}
You cannot have a function call like this:
MultiAnswer('+ questions[output] + ',' + answer[output]
+')
You will need to evaluate the parameter in a seperate variable and then pass it in the function.
So in your onClick call of multiAnswer you have wrapped the 3 inputs in quotes. After referencing your multiAnswer function you do have the 3 inputs that you are looking for. You also have + signs on the ends of those inputs. You do not need to concatenate the parens inside of the function call.
I hope this helps!
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
onClick = "MultiAnswer(questions[output] + ',' + answer[output]
)">Submit</button></p>';
I need help with file size on upload. i'd like to add file maximum size 2MB.
I use javascript code and i'm not good with javascript so if you guys can add file size into my code. Thanks.
var _validFileExtensions = [".jpg", ".jpeg", ".png"];
function Validate(oForm) {
var arrInputs = oForm.getElementsByTagName("input");
for (var i = 0; i < arrInputs.length; i++) {
var oInput = arrInputs[i];
if (oInput.type == "file") {
var sFileName = oInput.value;
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if (!blnValid) {
alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
return false;
}
}
}
}
return true;
}
This is the code I ended up writing
It can still be optimized in various ways, so its open for any performance, semantic or refactoring edits. I am not an expert.
Code Explained
In var _maxFilsize you have to write size of max file size to be allowed in bytes.
Function Validate has parameter oForm which expects an HTML object, through which it can search for input fields.
Store all input elements in an array, arrInputs.
Store value of arrInputs[i].type in string form in variable inputType
Compare the value of inputType with different input types in if/else statements.
When condition is met, each block returns a function that validates the matched input field
Function validateImage takes an argument which is simply the input field's property that contains list of files selected by user, arrInputs[i].files.
In validateImage Function there is a for loop that iterates over the list of files and validates their type and size, and returns true or false depending upon validity of file.
Code
var _maxFilesize = 2000000;// in bytes
function Validate(oForm) {
var arrInputs = oForm.getElementsByTagName("input");
var inputType;
var i = 0;
var arrLength = arrInputs.length;
for (i; i < arrLength; i++) {
inputType =arrInputs[i].type.toString();
if (inputType === "file"){
return validateImage(arrInputs[i].files);//calls function for validating image
}else if(inputType === "email"){
//call email validating function
}//add validation for more fields
}
}
function validateImage(file){
var j = 0;
var NumberOfFiles = file.length;
for(j; j< NumberOfFiles;j++){
if ((file[j].type === "image/jpeg" || file[j].type === "image/png")&& (file[j].size)<= _maxFilesize){
return true //or whatever you want to do here like calling a function to upadate view, or something
}
else{
return false //or whatever you want to do here like calling a function to upadate view, or something
}
}
}
I have a function that performs a Luhn check on a card entry when a form is posted.
<script language="javascript">
function Calculate(Luhn)
{
var sum = 0;
for (i=0; i<Luhn.length; i++ )
{
sum += parseInt(Luhn.substring(i,i+1));
}
var delta = new Array (0,1,2,3,4,-4,-3,-2,-1,0);
for (i=Luhn.length-1; i>=0; i-=2 )
{
var deltaIndex = parseInt(Luhn.substring(i,i+1));
var deltaValue = delta[deltaIndex];
sum += deltaValue;
}
var mod10 = sum % 10;
mod10 = 10 - mod10;
if (mod10==10)
{
mod10=0;
}
return mod10;
}
function Validate(Luhn)
{
var LuhnDigit = parseInt(Luhn.substring(Luhn.length-1,Luhn.length));
var LuhnLess = Luhn.substring(0,Luhn.length-1);
if (Calculate(LuhnLess)==parseInt(LuhnDigit))
{
return true;
}
alert("\n\nYou have mis-typed your card number! \nPlease check and correct.\n\n")
return false;
}
I also have a function that removes any spaces that may have been entered in the card number onblur.
function stripChar(sValue, sChar) {
var i, tempChar, buildString;
buildString = ""
for (var i=0; i<sValue.length; i++) {
tempChar = sValue.charAt(i);
if (tempChar != sChar) {
buildString = buildString + tempChar;
}
}
return buildString;
How do I combine the functions so that the spaces are removed and the card number checked onblur.
In your onblur function you could use:
Validate(stripChar(sValue, sChar));
I have the following code that worked fine till now as I decided to add more variables to the form. How can I make this function smart and itterate and pass all the variables in the form?
function getquerystring(strFormName) {
var form = document.forms[strFormName];
var word = form.clock_code.value;
qstr = 'clock_code=' + escape(word); // NOTE: no '?' before querystring
return qstr;
}
complete JS code # pastie
It looks like you're serializing a form to a querystring? If that's the case, then this is one place where a JavaScript library is really nice.
Each of these will serialize the first form on the page to a querystring.
// ExtJS
var str = Ext.lib.Ajax.serializeForm(Ext.select('form').elements[0]);
// jQuery
var str = $("form").serialize();
// MooTools
var str = $$('form').toQueryString();
// PrototypeJS
var str = $$('form')[0].serialize();
You can see some other methods and how they compare at http://jquery.malsup.com/form/comp/
Try this
function formToQueryString(form) {
var elements = form.elements;
var cgi = [];
for (var i = 0, n = elements.length; i < n; ++i) {
var el = elements[i];
if (!el.name) { continue; }
if (el.tagName === 'INPUT' && (el.type === 'checkbox' || el.type === 'radio')
&& !el.checked) {
continue;
}
cgi.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value));
}
return cgi.length ? '?' + cgi.join('&') : '';
}
The issue with your code is that you're only grabbing the clock_code element value, and ignoring the rest. Here's a replacement I wrote up:
function getquerystring(strFormName) {
var qstr = '', word = '';
var key = 0;
var form = document.forms[strFormName];
var fields = ['clock_code', 'message', 'type'];
for (var i = 0; i<fields.length; i++) {
key = fields[i];
word = form[key].value;
if (qstr && qstr.length > 0) {
qstr += '&';
}
qstr += encodeURIComponent(key) + '=' + encodeURIComponent(word);
}
return qstr;
}
Benjamin's approach is a bit more flexible; mine only queries those fields specifically named in the fields array
Assuming they are all simple fields, the following should work just fine (didn't test it, though - sorry if it doesn't "compile"):
function getquerystring(strFormName) {
var qstr = '';
var form = document.forms[strFormName];
var elements = form.elements;
var first = true;
for (elem in elements) {
var word = elem.value;
var name = elem.name;
if (first) {
first = false;
} else {
qstr = qstr + '&';
}
qstr = qstr + name + '=' + escape(word);
}
return qstr;
}
Adding info on supporting multiple Element types:
The question only mentioned text fields so I assumed the easier answer would suffice. Wrong!
Glad you're able to use JQuery (which rocks), but for completeness I'll just flesh this out with a bit of info on how to build your own "dynamic form handler".
First, you have to add checking on the class of elem, like so:
function isCheckbox(o){ return (o && o.constructor == Checkbox) }
and you have to then do something a little different depending on the type of object you are looking at.
For example:
for (var elem in elements) {
var value = '';
var name = elem.name;
if (isCheckbox(elem)) {
value = elem.checked ? 'true' : 'false';
} else if (isSingleSelect(elem)) {
var index = elem.selectedIndex;
if(selected_index > 0) {
value = elem.options[selected_index].value;
}
}
}
There may be situations where you have to turn values into something that is meaningful to your app, like in a multiple-select combo box. You could send one name=value pair for each value or roll them into a comma-seperated list or the like - it all depends on your app. But with this approach one can certainly build the "dynamic form handler" that fits their specific needs.
Check out this article for helpful stuff about how to process each form field type: http://www.javascript-coder.com/javascript-form/javascript-get-form.htm