admin管理员组

文章数量:1317897

I have this code:

<PlaceHolder>
<div class="greenDiv">
  <asp:TextBox ID="a"  runat="server" />
</div>
<div  class="greenDiv">
  <asp:TextBox ID="ab" runat="server" />
</div>
</PlaceHolder>

I need to let the user know if he left a Textbox empty, I tried something like this.. (not working) What have I missed?

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

I have this code:

<PlaceHolder>
<div class="greenDiv">
  <asp:TextBox ID="a"  runat="server" />
</div>
<div  class="greenDiv">
  <asp:TextBox ID="ab" runat="server" />
</div>
</PlaceHolder>

I need to let the user know if he left a Textbox empty, I tried something like this.. (not working) What have I missed?

 $('.greenDiv > input:text').blur(function () {
   if (!$(this).val()) {
     alert("fill this field");
   }
 });
Share Improve this question edited Jul 16, 2017 at 6:39 Cœur 38.8k26 gold badges205 silver badges277 bronze badges asked Dec 16, 2014 at 14:48 DamkululDamkulul 1,4764 gold badges32 silver badges70 bronze badges 0
Add a ment  | 

5 Answers 5

Reset to default 4

Try using input[type=text] instead

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

Try this

    <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>

below is Jquery

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

Try this:

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

Your selector is fine. When you use !$(this).val() you allow inputs with spaces (or any other invisible character) to fall through. An input with a single space is technically not empty. Try $.trim(something) === '' instead.

Instead of input:text you should use input[type=text]

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

本文标签: javascriptHow to check if a specific textbox under a specific div is emptyStack Overflow