Javascript Multiple Input Textbox Validation
Solution 1:
If you already have the textboxes in an array, loop through the array and look for duplicate values. This is not the most efficient way (it's O(n) to compute) to solve the problem (a dictionary would be better), but for a small number of text boxes it is the simplest.
function TestForDuplicates( var Textboxes )
{
for( tb in Textboxes )
{
for( tb2 in Textboxes )
{
if( tb != tb2 ) // ignore the same textbox...
{
if( tb.value == tb2.value )
alert( "The value " + tb.value + " appears more than once." );
}
}
}
}
If you have more than about 10 textboxes in your array, an alternative approach is to build a mapping of how many times each value appears:
function FindDuplicates( var Textboxes )
{
var valueList = new Array();
for( tb in Textboxes )
valueList.push( tb.value );
valueList.sort(); // sort values so that duplicates are adjacent
if( valueList.length > 1 )
{
for( i = 0; i < valueList.length-1; i++ )
if( valueList[i] == valueList[i+1] )
alert( "The value " + valueList[i] + " appears more than once." );
}
}
Solution 2:
function testValues ()
{
var inputs = document.getElementsByTagName ("input");
var answers= new Array();
for(var ii = 0; ii < inputs.length; ii++)
{
if(inputs[ii].type == 'text')
{
for(var jj = 0; jj < answers.length; jj++)
{
if(answers[jj] == inputs[ii].value)
return false;
}
answers.push(inputs[ii].value);
}
}
return true;
}
Solution 3:
Assuming you have code to read in the textboxes and store them in an array
var validator = function(textbox){
var values = [];
for(i=0;i<textbox.length;i+=1){
if (values.indexOf(textbox[i]) === -1){
values[i] = textbox[i];
}else{
return false;
}
}
return true;
}
That should be very performant as it only goes until it finds a duplicate
Solution 4:
This is pretty easy using a PrototypeJS Hash object.
function validate() {
var textVals = new Hash();
$$('input[type=text]').each( function(elem) {
if(textVals.get(elem.value) == undefined) {
textVals.set(elem.value, elem.id);
}else {
alert('Duplicate text value found (' + elem.id + '=' + textVals.get(elem.value) + ')');
}
});
}
This function iterates over all text inputs on the current page. If a value has never been seen before, it gets saved to the hash. If the value is already in the hash, we have a duplicate.
In this example, it displays the ids of the two elements with duplicate values.
Post a Comment for "Javascript Multiple Input Textbox Validation"