Javascript form validation - javascript

I'm wondering, Is there a JavaScript command (whats the proper name for the thing im looking for?) where I can select all input boxes in a form rather than just one?
E.g:
function checkform(id){
var theForm = document.getElementById( id );
if (theForm.surname.value == '') {
alert( "you didn't type in your surname");
theForm.surname.focus();
return false;
}
else if (theForm.surname.value.length == 0) {
alert( 'You\'ve left some of the fields blank' );
theForm.surname.focus();
return false;
}
return true;
}
I have this code. The purpose of it is that it checks each input box in the form to see if information has been entered, and if it hasn't, an alert appears when the user submits the form.
Is there a way I could change this piece of JavaScript in order to check every input box and not just the surname one (as seen in the example).

The method getElementsByTagName can give you all the inputs, the elements property will hold a NodeList of all the controls in a form.
var nodeList = theForm.getElementsByTagName('input');
or
var nodeList = theForm.elements;

I think you need the document.getElementsByTagName() method for this one. You could link this up with your current function like so:
var inputs = document.getElementsByTagName('input'), // get all input tags in the document
i = 0, // set counter to zero
l = inputs.length; // get number of inputs you have found
for (i; i < l; i += 1) { // loop through the inputs you have found
checkform(inputs[i].id); // send the id of each input to the `checkform` method
}
Of course you might want to rewrite the function you have to make it more efficient, but you could potentially drop this straight into your code (outside the checkform function) and it should do what you want.

Related

How can I add javascript to a PDF document to count the number of checked boxes and enter the value into a textbox area?

So I have a PDF doc that has 25 check boxes called "cb1" through "cb25". I would like to be able to count the number of boxes that are checked and put that count into a text box area called "Points".
I'm not very familiar with either JS or PDF form creation but from what I've been able to dig up I think I'm close to getting it to work.
I have added the following code to the document level:
function CountCheckBoxes(aFieldsNames) {
// count field names that have been selected
var count = 0;
// loop through array of field names
for (i = 0; i < aFieldNames.length; i++) {
// for field names with a value of not Off increment counter
if (this.getField(aFieldNames[i]).value != "Off") count++;
} // end loop of field names
// return count
return count;
} // end CountCheckBoxes
I've tried adding the following code text box properties to execute JS on mouse up and as a calculated value, neither of which seem to work to populate the text box with a count of checked boxes.
// var define field names to be tested
var aFields = new Array('cb1', 'cb2', 'cb3', 'cb4', 'cb5', 'cb6', 'cb7', 'cb8', 'cb9', 'cb10', 'cb11', 'cb12', 'cb13', 'cb14', 'cb14', 'cb15', 'cb16', 'cb17', 'cb18', 'cb19', 'cb20', 'cb21', 'cb22', 'cb23', 'cb24', 'cb25');
// count field names that have been selected
event.value = CountCheckBoxes(aFields);
The code below should be added to the text field that keeps count of the boxes. To do so, right click on the form field then Properties -> Calculate -> Custom Calculation Script -> "Edit...".
var sum = 0;
for ( i = 1; i < 26; i++ ) {
f = "cb" + i;
field = getField(f);
if (field.isBoxChecked(0)) {
sum = sum + 1;
}
}
event.value = sum;
This is tested and working in an actual document. Here are some details about the code:
There is a loop that goes over all 25 fields, and creates a string for each one of their names. The string values are "cb1", "cb2" etc. Then gets the field by name. The isBoxChecked(0) field method, will return true if the box is checked. If a box is checked, the code will bump up the sum of all checked fields. When it's all done, the sum is assigned to the current text field.
Here is a link to the JS for Acrobat reference. It's quite useful when putting together samples like the one above.

Am I using indexof correctly?

I'm trying to use indexof to tell me if a string appears on page.
The function below should cycle through all checkboxes (name="comment") in my form checking for each checkbox's value within the rest of the document (only because I can't figure out how to search just one span). If the string value is found to exist elsewhere on the page, that checkbox will change css style.
function loop() {
var comment=document.forms[0].comment;
var ii;
for (ii=0;ii<comment.length;ii++) {
str=comment[ii].value;
id = comment[ii].id;
if(document.body.innerHTML.toString().indexOf(str) !=-1)
{
document.getElementById(id).style.visibility = "hidden";
}
}
}
The result is that all checkboxes turn "hidden". I thought the problem was the checkbox finding its own value in the HTML, but the same happens when I search for nonsense.
Am I using indexof incorrectly? Can anyone point out how and where? I don't want to use window.find.
To elaborate:
Checkbox 1 value is "A IS FOR APPLE". Check the page for the string "A IS FOR APPLE". If found, make checkbox 1 hidden. Go to checkbox 2 and repeat.
If I understood what are you trying to do, I think a better approach should be something like this:
function loop() {
var inputs = document.getElementsByTagName("input");
var span = document.getElementsById("txtHint");
for(var i = 0; i < inputs.length; i++) {
//Let's check only the checkbox with the name comment
if(inputs[i].name == "comment" && inputs[i].value == span.innerText) {
inputs[i].style.visibility = "hidden";
}
}

How to detect if a user input has been repeated?

I'm trying to make hangman in javascript and I want to check if the user has used a letter already. I made a var letterGuessValue = to 0 and if they add an input it = 1. I know this would say know to everything if i got it to work (it doesn't even do anything) but am I on the right track maybe? Here's my code. http://jsbin.com/aWOnAfe/5/edit
I would say add an input to a list and whenever they add another input (aka letter), check this list to see if it is already in there. If it is, then its because they've already used that letter before. If not, then it is a new letter.
I don't see where the difficult part is.
http://jsfiddle.net/DerekL/jgqQ9/
Sample code
var used = {};
$("input").keyup(function(){
var val = this.value;
alert( used[val] ? "Used" : "Not used" );
this.value = "";
used[val] = true;
});
How it works
Assign true to used.LETTER when a letter is entered. Before assigning it though, if it was undefined then it hasn't been used. If it is true then it is used.
Sometimes developers tend to use an Array to record pressed keystrokes when doing key combinations, but in this case, iterating an Array would require both more memory and computation power. A simple object is an enough fit.
Use an array to store all of the used letters and function like this to add new ones.
var inputs = []
function addLetter(letter){
var used = false;
for(var i = 0; i < inputs.length; i++){
if(inputs[i] == letter){
used = true;
break;
}
}
if(!used){
inputs.push(letter);
}
}
The easiest way is to append each letter to a string, like this:
var letters = '';
var letterPressed = 'X'; // uppercase it if appropriate for your language
if (letters.indexOf(letterPressed) > -1)
{
// you already pressed it
}
else
{
letters += letterPressed;
}
You can also use an array to store your list of presses, although IMO that's overkill.

JavaScript validation, prevent duplicate input fields

I have a form with 10 Select Lists all have the same items. The items are populated from a PHP/MySQL array. The user needs to select one item per select list. I need to prevent the user from selecting the same item twice before submitting the form.
function checkDropdowns(){
var iDropdowns = 10;
var sValue;
var aValues = new Array();
var iKey = 0;
for(var i = 1; i <= iDropdowns; ++i){
sValue = document.getElementById('test' + i).value;
if ( !inArray(sValue, aValues) ){
aValues[iKey++] = sValue;
}else{
alert('Duplicate!');
return false;
}
}
return true;
}
Use javascript to add an event listener on the value change of the selects. That function would then loop through the selects taking the values into memory after having compared it to the values it had already. If the loop finds that the current select has an option that is already selected, put it back to default value and display a little message...
Or, still on a change event, take the value of the just selected item and remove all the items of this value in the 10 selects. So at the end the user will only have 1 choice, since he only sees the options he can choose. But be careful, if the user changes his mind on one select, make sure you add back the option you removed in the first place.
Option 2 is to be prefered as a user point of view, you will cause less frustration.
EDIT:
The code you are providing already does quite a lot... All you need now is something to revert the change if it is invalid:
var defaultValues = [];
function onLoadSelect(){//Please execute this on document load, or any event when the select are made available.
var iDropdowns = 10;
var iKey = 0;
for(var i = 1; i <= iDropdowns; ++i){
var sValue = document.getElementById('test' + i).value;
defaultValues['test' + i] = sValue;
}
}
Then, in your function's else, reset the value according to the defaults we have gathered:
else{
alert('Duplicate!');
document.getElementById('test' + i).value = defaultValues['test' + i];
return false;
}
I have written code, i think it can be improved but it works as you asked.
Put it in inside script tag under body so it loads after document.
Put id names of select/dropdown elements in id array.
Take a look: //took me 3 hours O_O
http://jsfiddle.net/techsin/TK9aX/15/
i think i need better strategy to approach programming.

validate 2 dropdowns (only some combinations valid)

I am completely new to JavaScript.
I have size and color dropdowns on a page for users to order a product, but only certain combinations are available i.e. pink is the only color in large sizes.
I thought I'd make an array of allowed sizes and test the user input against these.
If the choice is invalid then I want a popup to tell the user why.
In the real world I'll use SQL & PHP to create the array of allowed choices, in the example below I've hard coded 3 valid choices for testing. Unfortunately the code below doesn't do anything.
I'm sure it's a simple newb mistake. I really don't know what I'm doing :)
Can somebody help me out?
The validation function is supposed to happen when user clicks the form submit...
<form id="form1" name="form1" method="post" onsubmit="return validate_form()"
action="cart.php">
Here's the function:
<script type="text/javascript">
function validate_form() {
var allowed = new Array();
allowed[0]="10,beige";
allowed[1]="10,black";
allowed[2]="10,pink";
var chosenColInd = document.getElementById("colID");
var chosenColText = colID.options[colID.selectedIndex].text;
var chosenSizeInd = document.getElementById("sizeID");
var chosenSizeText = sizeID.options[sizeID.selectedIndex].text;
var chosenSizeCol = chosenSizeText+","+chosenColText;
var found = "false";
for ( var i = 0; i < allowed.length; i++ ) {
if (allowed[i]=chosenSizeCol) {
found = "true";
}
}
if (found = "false") {
alert( 'The variation you have selected is currently unavailable. Please select another.' );
return false;
} else {
return true;
}
}
</script>
There are a few lines where you use the assignment operator (that is single equals =) instead of one of the equality operators (that is double or triple equals, triple is usually preferred in JavaScript). Example:
if (found = "false") {
Would appear to be the problem at first sight - it's an assignment not a comparison :) use triple equals === instead of single:
if(found === "false") {
Also, consider the following (commented) updates to your code, which reflects more the typical style of JavaScript code:
function validate_form() {
//no need to use new Array(), use array literal instead
var allowed = [
"10,beige",
"10,black",
"10,pink"
];
var chosenColInd = document.getElementById("colID");
var chosenColText = colID.options[colID.selectedIndex].text;
var chosenSizeInd = document.getElementById("sizeID");
var chosenSizeText = sizeID.options[sizeID.selectedIndex].text;
var chosenSizeCol = chosenColText+","+chosenSizeText;
var found = "false";
for ( var i = 0; i < allowed.length; i++ ) {
//use equality operator instead of assignment
if (allowed[i]===chosenSizeCol) {
found = true; //may as well use a boolean rather than string
break; //exit loop early, no need to continue if we've already found
}
}
if (!found) { //no need to do a comparison with already boolean values
alert( 'The variation you have selected is currently unavailable. Please select another.' );
}
//may as well just return found here now that we're using a boolean
return found;
}

Categories

Resources