0

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('Field:' + this.id + ' is mandatory!');
            }
        });
    });

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Assuming you're using jquery:

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

Comments

1

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!');
            }
        });
    });

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.