如何检查特定div下的特定文本框是否为空

5
我有这段代码:
<PlaceHolder>
<div class="greenDiv">
  <asp:TextBox ID="a"  runat="server" />
</div>
<div  class="greenDiv">
  <asp:TextBox ID="ab" runat="server" />
</div>
</PlaceHolder>

我需要让用户知道他是否留空了文本框,我尝试过这样的代码..(不起作用)我错过了什么吗?
 $('.greenDiv > input:text').blur(function () {
   if (!$(this).val()) {
     alert("fill this field");
   }
 });
5个回答

4
尝试使用input[type=text]代替。
$('.greenDiv>input[type=text]').blur(function () {
    if (!$.trim($(this).val())) {
        alert("fill this field");
    }
});

不起作用。我将它添加到 $(document).ready() 函数中了,这有关系吗? - Damkulul
不,它可以添加在 ready() 中。你添加了jQuery吗?请检查控制台以查看是否出现任何错误! - MH2K9
小心空格和不可见字符。我知道你已经接受了这个答案,但还是看看我的吧。 - Ayman Safadi
谢谢,我也会使用你的答案 :-) - Damkulul

3
$('.greenDiv > input[type=text]').on('blur', function (e) {
  if (!$(e.currentTarget).val()) alert('fill this field');
});

1
尝试这个。
    <PlaceHolder>
<div class="greenDiv">
  <asp:TextBox ID="a" class="x"  runat="server" />
</div>
<div  class="greenDiv">
  <asp:TextBox ID="ab" class="x" runat="server" />
</div>
</PlaceHolder>

以下是jQuery。
 $('.greenDiv .x').blur(function () {
                if (!$(this).val()) {
                    alert("fill this field");
                }
            });

1

试试这个:

$('.greenDiv > input:text').blur(function () {
    if ($.trim($(this).val()) === '') {
        alert("fill this field");
    }
});

您的选择器很好。当您使用!$(this).val()时,您允许带有空格(或任何其他不可见字符)的输入通过。只有一个空格的输入在技术上不是空的。请尝试改用$.trim(something) === ''

1

你应该使用 input[type=text] 代替 input:text

$('.greenDiv>input[type=text]').on("blur",function () {
                if (!$(this).val()) {
                    alert("fill this field");
                }
            });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="greenDiv">
  <input type="text">
</div>
<div class="greenDiv">
  <input type="text">
 
</div>


文本框位于两个不同的div中,这两个div具有相同的类名“greenDiv”,每个div中都有一个文本框。 - Damkulul

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接