Facebook

Friday, February 3, 2012

jQuery: exclude $(this) from selector


I have a set of text boxes and i want to check for duplication of set values in any of the text box. ie, no text box should contain a value that is entered in any other.

HTML
<form method="post" action="" onsubmit="return validate()">
   <table>
       <tr>
               <td>
                         <input type="textkbox" name="priority[]" />
               </td>
       <tr>

       <tr>
               <td>
                         <input type="textkbox" name="priority[]" />
               </td>
       <tr>

       <tr>
               <td>
                         <input type="textkbox" name="priority[]" />
               </td>
       <tr>

       <tr>
               <td>
                         <input type="textkbox" name="priority[]" />
               </td>
       <tr>

       <tr>
               <td>
                         <input type="textkbox" name="priority[]" />
               </td>
       <tr>
   </table>
</form>
DEMO

JAVASCRIPT


var firstError='';
function validate(){
     $('input[type="text"]').each(function(){
var mastrPriority=$(this);
$('input[type="text"]').not(this).each(function(){
var priority=$(this);
if(mastrPriority.val()==priority.val()){
  seterrormessage(mastrPriority,'Duplicate Priority Values.');
seterrormessage(priority,'Duplicate Priority Values.');
if(firstError==''){
alert("Priority Field should contain unique values.");
firstError=mastrPriority;
}
}
});

})
if(firstError!=''){
  firstError.focus();
return false;
}
else{
  return true;
}
}


function seterrormessage(field,msg){
var errorBox=$(field).parent().find('div.validationError').first();
if(errorBox.length>0){
  errorBox.text(msg);
}
else{
  $(field).after('</br><div class="validationError">'+msg+'</a>');
}
}
The function validate() iterates through each text box and compare values of each box with all others except current one. The current text box is excluded from the set of text boxes using .not(this).

No comments:

Post a Comment