Почему эта форма отправляется всегда ... Проверка JavaScript не работает - PullRequest
0 голосов
/ 12 октября 2011

Эта форма всегда отправляется, никогда не останавливайтесь на достигнутом с ошибками. Что не так?

спасибо заранее;)

Я поставил возвращаемый валидатор valida (this) .... и код javascript выглядит хорошо

<form name="formulario" id="formulario" method="POST" action="<%=request.getContextPath()%>/altaanuncio" onSubmit="return valida(this)">


function valida(f) {

        if (f.marca.selectedIndex==0){
            $('#errores').html('Seleccione la marca.');
            f.marca.focus();
         return false;
    }

        else if(f.garantia.value == ""){
            $('#errores').html('Introduzca meses de garantía');
            f.garantia.focus();
                return false;
        }

        else if(f.pvpofertado.value == ""){
            $('#errores').html('Introduzca el precio del coche');
            f.pvpofertado.focus();
                return false;

        }

     return true;
}

Ответы [ 2 ]

1 голос
/ 12 октября 2011

Я думаю, вы пытаетесь вызвать функции jQuery на простые элементы JS .Попробуйте это:

// When the DOM is ready:
$(document).ready(function() {

    // Attach submit event listener to form (== onSubmit)
    $('#formulario').submit(function(event) {

        // Get the jQuery object for the 'marca' field:
        var marca = event.target.children('#marca');

        if (marca.attr('selectedIndex') === 0) {
            $('#errores').text('Seleccione la marca.');
            marca.focus(); // <--this now works because it's a jQuery object.
            event.preventDefault(); // instead of return false;
        }
    });
});

<form id="formulario" />
1 голос
/ 12 октября 2011

Вы, очевидно, используете jQuery, поэтому используйте jQuery полностью

Здесь есть плагины проверки: http://zoomzum.com/useful-jquery-form-validation/

И пост здесь: http://api.jquery.com/jQuery.post/

<html>
<head>
<script type="text/javascript" src="jquery.latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
  $("#formulario").bind("submit",function(e) {
    var f = this; // or $(this) but then you need to test .val() and use find() or children
    if (f.marca.selectedIndex==0){
       $('#errores').html('Seleccione la marca.');
       f.marca.focus();
       e.preventDefault();
    }
.
.
.
.
   }
   $.post($(this).attr('action'),$(this).serialize(),
     success: function( response )  {
       console.log( response );
     }
   });
   e.preventDefault(); // cancel the actual submit       

  });
});
</script>
</head>
<body>
<form name="formulario" id="formulario" method="POST" action="<%=request.getContextPath()%>/altaanuncio">
...