Amran
Amran

Reputation: 657

Check Textarea Field Has Required Attribute

I want to check if a textarea field has the required attribute for validation purpose. When user click on submit, it will pop up the loading image. I want to make sure the image is hidden after it shows the validation message. Below are the codes,

HTML

<textarea id="title" style="width:100%; name="title" required></textarea>

jQUERY

$("#submit").on("click",function() {
    $("#loading").css("display", "block"); //display the image 
    return true;
});

May I know how to check if the required is true, the loading image will be hidden. I tried to do like below but with fail result.

$("#submit").on("click",function() {
    $("#loading").css("display", "block");
    return true;

    if ($("#title").prop("required",true)) {
        $("#loading").css("display", "none"); 
    } 
});

Upvotes: 0

Views: 302

Answers (3)

Kaja Mydeen
Kaja Mydeen

Reputation: 585

<script type="text/javascript">
   $("#submit").on("click",function() {
   if ($("#title").val() != '') {
        $("#loading").css("display", "none"); 
    }
    else {
        $("#loading").css("display", "block");
        setTimeout(function(){ $('#loading').fadeOut() }, 5000); 
    } 

});
</script>

How many seconds that image should display. I kept for five seconds.

Upvotes: 1

Jai
Jai

Reputation: 74738

As required is a property you can use .prop() as getter (when single argument) with combination of .toggle(condition):

$("#submit").on("click",function() {
    $("#loading").toggle(!$("#title").prop("required"));
});

Here .toggle(!true) in case if there is required property then !true will cause to hide the element.

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115232

You are updating the required property instead get it using prop(''required).

if ($("#title").prop("required")) {
   $("#loading").css("display", "none"); 
} 

Upvotes: 1

Related Questions