Tal Rofe
Tal Rofe

Reputation: 1834

How can I handle an empty input text?

I have the following:

<div>
                    <input class="amounts" type="text" placeholder="ENTER AMOUNT"/>
                    <a href="" data-id="@product.Id" class="btn btn-info btn-lg-add" style="margin-left:auto">
                        <span class="glyphicon glyphicon-shopping-cart"></span> ADD
                    </a><br />
                </div>

in jQuery script section, I'm trying to handle the case the user leaves it empty:

    $(".btn.btn-info.btn-lg-add").click(function(event){
....
    if ($(this).prev('input').val() == undefined || $(this).prev('input').val() == null) {
                url = '@Html.Raw(Url.Action("myHandler", "myControllerName"))';
.....
}

What am I doing wrong with this syntax? - because as the user leaves the text input as empty, it does not enters the if

Upvotes: 1

Views: 59

Answers (1)

Unmitigated
Unmitigated

Reputation: 89294

You can use this function to check if a String is null, empty, or contains only spaces:

function isNullOrEmpty(str){
  return !str.trim().length;
}

 $(".btn.btn-info.btn-lg-add").click(function(event){
    if (isNullOrEmpty($(this).prev('input').val())) {
       event.preventDefault();
       alert("Value can not be empty");
    }
});
function isNullOrEmpty(str){
  return !str.trim().length;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
                    <input class="amounts" type="text" placeholder="ENTER AMOUNT"/>
                    <a href="" data-id="@product.Id" class="btn btn-info btn-lg-add" style="margin-left:auto">
                        <span class="glyphicon glyphicon-shopping-cart"></span> ADD
                    </a><br />
                </div>

Upvotes: 1

Related Questions