tags:

views:

827

answers:

3

I have n number of textboxes on a form. After the user enters a value in a textbox, I need to check that it's not a duplicate of any of the other textboxes. For example:

Textbox[0] : 1
Textbox[1] : 2 
Textbox[2] : 3
Textbox[4] : 1

It should alert saying that '1' has been entered twice.

I tried the following:

function findDuplicates ( obj ) {
    var inputs = document.getElementsByName('analog_idorder[]');
    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)
                    alert('Duplicate Id_order number');
                return false;
            }
            answers.push(inputs[ii].value);
        }
    }
    return true;
}

But only the first two textboxes validate.

Let me know how I can solve this problem.

+1  A: 

Try adding brackets for the if statement in the nestled loop:

            for(var jj = 0; jj < answers.length; jj++){
                if(answers[jj] == inputs[ii].value){
                   alert('Duplicate Id_order number');
                   return false;
                }

            }

Else the loop will always return false at the first iteration.

Baversjo
Thanks Baversjo i Will try out and let you know
boss
+1  A: 

You could get rid of all the looping you are doing by using a associative array to store the values you've seen:

var answers = document.getElementsByName("analog_iorder[]");
var seen = {};

function checkForDupes() {
  for (var i=0;i<answers.length;i++) { 
    if (seen[ answers[i].value ]) { 
      alert("Duplicate "); 
      return false;
    } 
    seen[ answers[i].value ] = true; 
  }
  return true;
}
seth
A: 
Text 1: <input type="text" id="txt1" onblur="chkValue('txt1');" /><br/>
Text 2: <input type="text" id="txt2" onblur="chkValue('txt2');" /><br/>
Text 3: <input type="text" id="txt3" onblur="chkValue('txt3');" /><br/>
Text 4: <input type="text" id="txt4" onblur="chkValue('txt4');" /><br/>
Text 5: <input type="text" id="txt5" onblur="chkValue('txt5');" /><br/>
Text 6: <input type="text" id="txt6" onblur="chkValue('txt6');" /><br/>
Text 7: <input type="text" id="txt7" onblur="chkValue('txt7');" /><br/>
Text 8: <input type="text" id="txt8" onblur="chkValue('txt8');" /><br/>
Text 9: <input type="text" id="txt9" onblur="chkValue('txt9');" /><br/>
Text 10: <input type="text" id="txt10" onblur="chkValue('txt10');" /><br/>

<script type="text/javascript">
var vals=new Object();

function chkValue(a)
{
    var t=document.getElementById(a);

    if(vals[t.value])
    {
        if(vals[t.value] != a)
        {
            alert("You have already entered ["+t.value+"]");
            t.value="";
        }
    }
    else
    {
        vals[t.value] = a;
    }
}

</script>
TheVillageIdiot