2013-08-27 19 views
0

我正在设计一个获取用户信息然后转到另一个页面的表单。有很多“输入文本”控制来填充。用户必须填写所有“输入文本”控件才能返回主页。如果控件为空,则应在“输入文本”中放置“x”图标。如何在html中为相同类型的控件编写jquery函数?

我的主要问题是,我在jQuery的新的,我不想写这个功能对于每个控制:

$('#send').click(function() { 
      if ($('#kname').val().length == 0) { 
       $('#kname').css({ background: "url(image/error.png) no-repeat right" }); 
      } 
     }); 

我需要所有控件的通用功能。这里是我的html行:

//some code 
     <input type="text" id="knumber" /> 
     <input type="text" id="kname" /> 
     <input type="text" id="ksurname" /> 
    //some other code 

编辑:我使用“输入按钮”发送这些信息。

<input type="button" value="Send Them" id="send" /> 

回答

1

尝试验证与text类型的所有输入元件下面

$("input[type=text]").filter(function() { 
    return $.trim(this.value).length == 0 
}).css({ 
    background : "url(image/error.png) no-repeat right" 
}); 

作为给定的或添加一个类的那些希望验证等not-empty然后

元件
<input id="kname" type="text" class="not-empty" /> 
<input id="ksurname" type="text" class="not-empty" /> 

then

$(".not-empty").filter(function() { 
    return $.trim(this.value).length == 0 
}).css({ 
    background : "url(image/error.png) no-repeat right" 
}); 
+0

@AliSağırvelioğulları更好,如果你删除其他问题 –

0

怎么样?

$("#send").click(function() { 
    $("input[type=text]").each(function(){ 
      if ($(this).val().length == 0) { 
       $(this).css({ background: "url(image/error.png) no-repeat right" }); 
      } 
    }); 
}); 

例如:http://jsfiddle.net/ddDSB/

0
//some code 
<input class="validate" type="text" id="knumber" /> 
<input class="validate" type="text" id="kname" /> 
<input class="validate"type="text" id="ksurname" /> 
//some code... 


$(".validate").click(function(){ 
    ... 
}); 
+0

我需要点击一个按钮类型,而不是文本... –

0

尝试使用此 一个类名“requiredField”添加到您的所有文本字段

在你点击按钮的方法

找到所有的文本框

textboxes = $('#formid').find('.requiredField'); 

然后用各种方法。

textboxes.each(function() { 
if(this.value.length==0){ 
    $('#kname').css({ background: "url(image/error.png) no-repeat right" }); 
    //do something here 
} 
} 
+0

,我应该写这个方法到我的按钮的点击事件? –

+0

@AliSağırvelioğulları是的,我在第二行提到它 – Rex

3

有关使用$.each,并通过所有文字循环什么elemnts

$('#send').click(function() { 
     $("input[type=text]").each(function(){ 
      if ($(this).val() == '') { 
       $(this).css({ background: "url(image/error.png) no-repeat right" }); 
      } 
     }); 
相关问题