jquery - Reusing the same function in javascript for elements using the same classes not working -


javascript:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <script>     $(document).ready(function(){     $("#first").keyup(function(event){         event.preventdefault();         ajax_check("#first");     });     $("#last").keyup(function(event){         event.preventdefault();         ajax_check("#last");     }); }); function ajax_check(current) {     var check=$(current).val();     $.post("validate.php", {tocheck : check}, function(filled) {         if(filled == '1')         {                $(".check").html("");             $(".ajax_check").removeclass("error");             $(".ajax_check").addclass("success");         }         else          {             $(".check").html("");             $(".ajax_check").removeclass("error");             $(".ajax_check").removeclass("success");         }     }) } 

html

<div class="control-group ajax_check">     <label class="control-label" for="first">first name</label>     <div class="controls">         <input type="text" id="first" class="validate" placeholder="first" required>         <span class="help-inline check" ></span>     </div> </div> <div class="control-group ajax_check">     <label class="control-label" for="last">last name</label>     <div class="controls">         <input type="text" id="last" class="validate" placeholder="last" required>         <span class="help-inline check" ></span>     </div> </div> 

the issue i'm having when enter in info 1 of input, other 1 gets highlighted too, isn't suppose happen. , think code kind of sloppy, i'm trying reuse ajax_check function instead of making function each input field.

is there way reuse function both of inputs? i'm new javascript, i'm kind of lost. thank you!

http://i.imgur.com/bilobrf.png

it has scope you're requesting .check within in ajax call. you're going document-level (instead of within current node). simple change makes work intended:

var $this = $(current), // store reference jquery object     $scope = $this.closest('.ajax_check'), // set scope .ajax_check     check = $this.val(); $.post("validate.php", {tocheck : check}, function(filled) {     if(filled == '1')     {         // use .find() search _within_ $scope , not across         // entire document.         $scope.find(".check").html("");         $scope.removeclass("error").addclass("success");     }     else      {         // same thing, search within $scope         $scope.find(".check").html("");         $scope.removeclass("error success");     } }) 

you can refactor bindings bit make little more brief well:

$("#first,#last").keyup(function(event){     event.preventdefault();     ajax_check(this); // automatically going #first or #last                       // selector above }); 

Comments