开发者

jQuery Class Selector Problem

开发者 https://www.devze.com 2023-02-09 01:45 出处:网络
I\'m trying to write code that makes an alert sound if focus has left the text field with a class \"mandatory\", and that field is empty.

I'm trying to write code that makes an alert sound if focus has left the text field with a class "mandatory", and that field is empty.

Basically if a user leaves a mandatory text field without writing anything, it will prompt them.

Here's my code, it doesn't work:

    $(document).ready(function(){
        $('.mandatory').blur(function(){
            if($(this.id).val() == "")
            {
                     alert(开发者_JAVA技巧'Field:' + this.id + ' is mandatory!');
            }
        });
    });


You're using this.id when you should be using this:

if($(this).val() == "")
{
    alert('Field:' + this.id + ' is mandatory!');
}

To explain: inside an event handler, this is the DOM element upon which the event was triggered. As you can see from the documentation for the $ function (note that the jQuery function and the $ function are the same thing), you can use a DOM element to build a jQuery selection.

Note that you could optimise this further by discarding the jQuery constructor and simply using this.value instead.


Assuming you're using jquery:

$(document).ready(function(){
    $('.mandatory').blur(function(){
        if($(this).val() == "") {
          alert('Field:' + $(this).attr('id') + ' is mandatory!');
        }
    });
});


Your code wont work if the user has entered white space

Use

$.trim()

instead

$(document).ready(function(){
        $('.mandatory').blur(function(){
            if($.trim($(this).val()) == "")
            {
                     alert('Field:' + this.id + ' is mandatory!');
            }
        });
    });


Guess you were tryin to do this

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>

<script>
$(function(){
    $('.mandatory').each(function (){
        $(this).blur(
        function(){
            if($(this).val() == ""){
                alert("empty");
            }
        })
    });

});
</script>


<div id='header'>
<input type="text" class="mandatory"/>
<input type="text" class="mandatory"/>
<input type="text" class="mandatory"/>
<input type="text" class="mandatory"/>
<input type="text" class="mandatory"/>
<input type="text" class="mandatory"/>
<input type="text" class="mandatory"/>
</div>

and this is working

0

精彩评论

暂无评论...
验证码 换一张
取 消