Randel Ramirez
Randel Ramirez

Reputation: 3761

How do I validate a form using jquery before ajax call?

What I'm trying to do is a validate a textbox and a hiddenfield, I have an autocomplete combobox from jquery ui wherein once the user has selected a value the value then will be stored inside a hidden field. The value of the hidden field is actually an ID of an item. Another input I want to validate is a textbox that should only contain numbers. The goal is to validate the user input before I call an $.ajax function otherwise prevent the save or do something else:

Here is my current code/script:

   Type product name:<input type="text" size="30" value="" id="itemName"  class="auto1" placeholder="Type Product Here" />
                      <input name="" type="hidden" value=""  id="itemId"/>
        </div>

        <p> Quantity<input id="itemQty" type="number"  name="txtQuantity" value="" width="200"></p>

        <p> 

           <a href="#" id="saveitem" style="position:relative; left:-280px;" class="bt_green"><span class="bt_green_lft"></span><strong>Add</strong><span class="bt_green_r"></span></a>

        </p>

  </form> 


$(document).on("click", "#saveitem", function (e) {
        e.preventDefault();
        var ItemId = $("#itemId").val().toString();
        var Qty = $("#itemQty").val().toString();
            $.ajax({

  url: "Functions.php",

  data: "ItemId="+ItemId+"&Qty="+Qty+"&Action=Add",
  cache: false,
  success: function(html){
      $("#items").empty(); 
     $("#items").hide();
    $("#items").append(html).fadeIn('slow');

    $("#itemName").val("");
    $("#itemId").val("");
    $("#itemQty").val("");

  }
});

    });

Sir/Ma'am your answers would be of great help and be very much appreciated.Thank you++

Upvotes: 0

Views: 1605

Answers (1)

Oyeme
Oyeme

Reputation: 11235

$(document).on("click", "#saveitem", function (e) {
        e.preventDefault();
        var ItemId = $("#itemId").val();
        var Qty = $("#itemQty").val();

           //validation is here
           if($("#itemQty").val() > 0){
            //your validation code is here
           }else {
                $.ajax({
                url: "Functions.php",
                data: "ItemId="+ItemId+"&Qty="+Qty+"&Action=Add",
                cache: false,
                success: function(html){
                    $("#items").empty(); 
                    $("#items").hide();
                    $("#items").append(html).fadeIn('slow');

                    $("#itemName").val("");
                    $("#itemId").val("");
                    $("#itemQty").val("");
                }
            });
           }

});

Upvotes: 1

Related Questions