-2

I need to create a re-useable function. The following script should prevent form submit and show a div alert. This version does not prevent form submit

<script type="text/javascript">
    function hide(obj) {
        var el = document.getElementById(obj);
        el.style.display = 'none';
    }
    $(function() {
        $('form#vendiendo').submit(function(e) {
            if (Number($("#venta").val()) <
                Number($("#costo").val())) {
                $("#warnings").show();

                //here start  the new code I added
                if (Number($("#cantidad").val()) >
                    Number($("#stock").val())) {
                    $("#warnings2").show();

                    //here ends the new code I added
                    return false;
                }
            });
        });
</script>
RobC
  • 22,977
  • 20
  • 73
  • 80
rorororor
  • 29
  • 4

1 Answers1

0

If you want to stop the form from submitting in the case of an error, this should do.

<script type="text/javascript">
function hide(obj) {
    var el = document.getElementById(obj);
    el.style.display = 'none';
}
$(function() {
  $('form#vendiendo').submit(function(e) {
    if(Number($("#venta").val()) < Number($("#costo").val())) {
      $("#warnings").show();
      // You're still in the first if() statement. Is that what you want?
      if (Number($("#cantidad").val()) > Number($("#stock").val())) {
        // At this point, both checks have failed. We want to stop the
        // default behavior.
        e.preventDefault();
        e.stopPropagation();

        // And tell the user why we failed.
        $("#warnings2").show();

        return false;
      }
    });
  });
</script>
Snowmonkey
  • 3,716
  • 1
  • 16
  • 16