2016-09-17 51 views
-1

我有12个ASP文本框和4个ASP按钮。在JQuery中获取按钮类

现在...我想要做的是..我想分组或关联3个文本框到每个按钮(使3个文本框和1个按钮的组)。我可以通过分别为3个文本框和1个按钮分配相同的类并将其他类分配给其他3个文本框和1个按钮来完成此操作。

现在我的任务是,如果我点击一个按钮的类是“必需的”,那么只有类为“必需”的文本框应该在Jquery中验证。请帮忙 !!

回答

0

试试这个:

如果每个去年3文本框为空,然后按button.Required显示信息要求。

$(document).ready(function(){ 

    $("button").on("click",function(){ 

     var cls = $(this).attr("class"); 

     if(cls == "Required") { 

      $("input[type=text]." + cls).each(function(){ 

       $(this).next("span").remove(); 
       if($(this).val() == '') 
        $(this).after("<span>Require</span>"); 
       })  
     } 
    }) 
}) 

最终代码:

<!DOCTYPE html> 
 
<html lang="en"> 
 
<head> 
 
    <style> 
 
    </style> 
 
</head> 
 
    <body> 
 
     
 
     <input type="text" class="txt1"> 
 
     <br> 
 
     <input type="text" class="txt1"> 
 
     <br> 
 
     <input type="text" class="txt1"> 
 
     <br><br> 
 
     
 
     <input type="text" class="txt2"> 
 
     <br> 
 
     <input type="text" class="txt2"> 
 
     <br> 
 
     <input type="text" class="txt2"> 
 
     <br><br> 
 
     <input type="text" class="Required"> 
 
     <br> 
 
     <input type="text" class="Required"> 
 
     <br> 
 
     <input type="text" class="Required"> 
 
     <br><br> 
 
     <button class="txt1">Click 1</button> 
 
     <button class="txt2">Click 2</button> 
 
     <button class="Required">Required</button> 
 
     
 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
 
     
 
     <script> 
 
      
 
     $(document).ready(function(){ 
 

 
      $("button").on("click",function(){ 
 

 
       var cls = $(this).attr("class"); 
 

 
       if(cls == "Required") { 
 

 
        $("input[type=text]." + cls).each(function(){ 
 

 
         $(this).next("span").remove(); 
 
         if($(this).val() == '') 
 
          $(this).after("<span>Require</span>"); 
 
         })  
 
       } 
 
      }) 
 

 
     }) 
 
      
 
     </script> 
 
    </body> 
 
</html>

+0

感谢ehsan的回答! 另外,我已经提到了我在下面写的代码。 –

0

希望thias会给你一些想法。

$(document).ready(function() { 
    $(document).on('click', 'button.required', function(e){ 
     e.preventDefault(); 

     var textBoxValue = $('input.required').val(); 
     alert(textBoxValue); 

     //Validation for the value goes here... 

    }); 
}); 

确保您在使用该功能之前包含了Jquery库。

0

我已经写了下面的代码,幸运的是我能够解决的目的。

$(document).ready(function() { 
     $('input[type="submit"]').click(function (e) { 
      var ClassName = $(this).attr('class');     
      var j = 0; 
      $('input.' + ClassName + '[type="text"]').each(function() { 

       if (this.value == "") { 
        this.style.backgroundColor = "Bisque"; 
        j++; 
       } 
      }); 

      if (j > 0) { 
       event.preventDefault(); 
      } 
     });