Ver Mensaje Individual
  #3 (permalink)  
Antiguo 28/04/2018, 22:36
eridamega
 
Fecha de Ingreso: enero-2013
Mensajes: 9
Antigüedad: 11 años, 3 meses
Puntos: 0
Respuesta: Problema con función Jquery

Cita:
Iniciado por Alexis88 Ver Mensaje
Cuando se ejecuta el código JavaScript, la variable productMainCategoryId toma el valor del <input> oculto (en este caso, 23) y la condición se evalúa. Como el conjunto de instrucciones se ejecutará si se cumple uno de los tres casos planteados en la condición y ya que el primero de ellos coincide, la variable nombre toma el valor del área de texto (vacía al inicio) y hace un llamado a la función, enviando los valores 0 y 20. En la función, la condición se termina cumpliendo puesto que 0 es menor a 20, por ende, se debe mostrar el primer mensaje de alerta.

No sé si en el documento hay uno o más formularios; pero, suponiendo que fuera el único, te aconsejaría lo siguiente:

1. [URL="http://api.jquery.com/on/"]Delega[/URL] el evento de envío ([URL="https://developer.mozilla.org/en-US/docs/Web/Events/submit"][inline]submit[/inline][/URL]) al formulario mediante jQuery:

Código Javascript:
Ver original
  1. $("form").on("submit", function(event){});

2. Cancela el envío usando el método [URL="https://developer.mozilla.org/es/docs/Web/API/Event/preventDefault"][inline].preventDefault()[/inline][/URL]:

Código Javascript:
Ver original
  1. $("form").on("submit", function(event){
  2.     event.preventDefault();
  3. });

3. Enseguida, obtén el valor de la primera variable y ejecuta la condición. En caso de cumplirse, envía al formulario como tercer argumento utilizando la palabra reservada [URL="https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Operadores/this"][inline]this[/inline][/URL]:

Código Javascript:
Ver original
  1. $("form").on("submit", function(event){
  2.     event.preventDefault();
  3.  
  4.     var productMainCategoryId = $('#productMainCategoryId').val();
  5.  
  6.     if (productMainCategoryId == 23 || productMainCategoryId == 27 || productMainCategoryId == 28){
  7.         $("small.float-xs-right").text('Limite 20 caracteres');
  8.  
  9.         //Almacenamos los valores
  10.         nombre = $('.product-message').val();
  11.  
  12.         validar(nombre.length, 20, this);
  13.     }
  14. });

4. Por último, en la función, en lugar de retornar valores booleanos, ejecuta el envío (en el caso de que se cumpla la condición de la función) utilizando el método [URL="https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit"][inline].submit()[/inline][/URL]:

Código Javascript:
Ver original
  1. function validar(largo, limite, form){
  2.     if (largo < limite){
  3.         alert('La formula funciono con ' + largo + '. texto agregado');
  4.         form.submit();
  5.     }
  6.     else{
  7.         $("small.float-xs-right").html("<span style='color: #ff0000;'>Se excede el limite permitido</span>");
  8.         alert('La formula funciono, pero te pasaste de los caracteres');
  9.     }
  10. }

Todo junto:

Código HTML:
Ver original
  1. <form method="post" action="">
  2.     <div>
  3.         <label> Marcado</label>
  4.         <p></p>
  5.  
  6.         <!-- Este es el ID  y varia depediendo de la página que abra para el ejemplo puse 23-->
  7.         <input type="hidden" id="productMainCategoryId" value="23">
  8.  
  9.         <textarea placeholder="marca aca" class="product-message" maxlength="250"  name="marcado"></textarea>
  10.         <small class="float-xs-right">Máximo 200 caracteres</small>
  11.         <p></p>
  12.        
  13.         <button class="btn btn-primary float-xs-right" type="submit" name="submitCustomizedData">guardar</button>
  14.     </div>
  15. </form>

Código Javascript:
Ver original
  1. function validar(largo, limite, form){
  2.     if (largo < limite){
  3.         alert('La formula funciono con ' + largo + '. texto agregado');
  4.         form.submit();
  5.     }
  6.     else{
  7.         $("small.float-xs-right").html("<span style='color: #ff0000;'>Se excede el limite permitido</span>");
  8.         alert('La formula funciono, pero te pasaste de los caracteres');
  9.     }
  10. }
  11.  
  12. $(document).ready(function(){ //Para que delegue el evento al cargar el DOM
  13.     $("form").on("submit", function(event){
  14.         event.preventDefault();
  15.  
  16.         var productMainCategoryId = $('#productMainCategoryId').val();
  17.  
  18.         if (productMainCategoryId == 23 || productMainCategoryId == 27 || productMainCategoryId == 28){
  19.             $("small.float-xs-right").text('Limite 20 caracteres');
  20.  
  21.             //Almacenamos los valores
  22.             nombre = $('.product-message').val();
  23.  
  24.             validar(nombre.length, 20, this);
  25.         }
  26.     });
  27. });

Fíjate que quité el onsubmit="... del <form>. Ya no se recomienda seguir trabajando con código JavaScript inline, es decir, insertado en los elementos HTML. Para eso puedes colocarlo en un archivo .js e incluirlo en el documento mediante el elemento <script>.

Hola Muchísimas gracias por tu respuesta has sido de mucha ayuda.
Me saltan varias dudas
La función es para una página prestashop, donde deseo que actúe la función hay varios submit, el de el el textarea de personalizacion el de agregar al carrito entre otros, al hacer clic en los otros submit no se activa la función?
Al cargar la página (sin hacer clic en el submit) debe aparecer este mensaje, y no aparece
que corresponde a
Código:
$("small.float-xs-right").text('Limite 20 caracteres');
3 Por fa podrias revisar esta, esta la hice yo es la que me ha funcionado al 100% no la uso porque el lint me arroja warings pero funciona correctamente
Código:
1 Unnecessary 'else' after disruption. } else {

2 Function statements should not be placed in blocks.Use a function expression or move the statement to the top of the outer function. (uso de función dentro de un if, es obligatorio corregir este warwing??
Esta es mi función hecha con muy poco conocimiento
Código HTML:
Ver original
  1. <form method="post" action="" onSubmit="return validar();">
  2.   <div>
  3.     <label> Marcado</label>
  4.     <p></p>
  5.     <input type="hidden" id="productMainCategoryId" value="29">
  6.     <textarea placeholder="marca aca" class="product-message" maxlength="250"  name="marcado"></textarea>
  7.     <br>
  8.     <small class="float-xs-right">Máximo 200 caracteres</small>
  9.     <p></p>
  10.     <button class="btn btn-primary float-xs-right" type="submit" name="submitCustomizedData">guardar</button>
  11.   </div>
  12. </form>
Código Javascript:
Ver original
  1. var productMainCategoryId = $('#productMainCategoryId').val();
  2.  
  3.  
  4. if (productMainCategoryId == 23 || productMainCategoryId == 27 || productMainCategoryId == 28) {
  5.     $("small.float-xs-right").text('Limite 20 caracteres');
  6.  
  7.     function validar() {
  8.         //Almacenamos los valores
  9.         limiteCaracter = $('.product-message').val();
  10.  
  11.         //Comprobamos la longitud de caracteres
  12.         if (limiteCaracter.length < 20) {
  13.             alert('La formula funciono. texto agregado');
  14.             return true;
  15.  
  16.         } else {
  17.             $("small.float-xs-right").html("<span style='color: #ff0000;'>Se excede el limite permitido</span>");
  18.             alert('La formula funciono, pero te pasaste de los caracteres');
  19.  
  20.             return false;
  21.         }
  22.  
  23.     }
  24.  
  25. } else if (productMainCategoryId == 29 || productMainCategoryId == 30 || productMainCategoryId == 31) {
  26.     $("small.float-xs-right").text('Limite 18 caracteres');
  27.  
  28.     function validar() {
  29.         //Almacenamos los valores
  30.         limiteCaracter = $('.product-message').val();
  31.  
  32.         //Comprobamos la longitud de caracteres
  33.         if (limiteCaracter.length < 18) {
  34.             alert('La formula funciono con 18. texto agregado');
  35.             return true;
  36.  
  37.         } else {
  38.             $("small.float-xs-right").html("<span style='color: #ff0000;'>Se excede el limite permitido</span>");
  39.             alert('La formula funciono, pero te pasaste de los caracteres');
  40.  
  41.             return false;
  42.         }
  43.  
  44.     }
  45. } else if (productMainCategoryId == 26) {
  46.     $("small.float-xs-right").text('Limite 18 caracteres');
  47.  
  48.     function validar() {
  49.         //Almacenamos los valores
  50.         limiteCaracter = $('.product-message').val();
  51.  
  52.         //Comprobamos la longitud de caracteres
  53.         if (limiteCaracter.length < 25) {
  54.             alert('La formula funciono con 25. texto agregado');
  55.             return true;
  56.  
  57.         } else {
  58.             $("small.float-xs-right").html("<span style='color: #ff0000;'>Se excede el limite permitido</span>");
  59.             alert('La formula funciono, pero te pasaste de los caracteres');
  60.  
  61.             return false;
  62.         }
  63.  
  64.     }
  65. } else if (productMainCategoryId == 24) { //Classic II 15 carac
  66.     $("small.float-xs-right").text('Limite 18 caracteres');
  67.  
  68.     function validar() {
  69.         //Almacenamos los valores
  70.         limiteCaracter = $('.product-message').val();
  71.  
  72.         //Comprobamos la longitud de caracteres
  73.         if (limiteCaracter.length < 15) {
  74.             alert('La formula funciono con 15. texto agregado');
  75.             return true;
  76.  
  77.         } else {
  78.             $("small.float-xs-right").html("<span style='color: #ff0000;'>Se excede el limite permitido</span>");
  79.             alert('La formula funciono, pero te pasaste de los caracteres');
  80.  
  81.             return false;
  82.         }
  83.  
  84.     }
  85. } else {
  86.     alert('El Id de la página actual es diferente al ID del la formula');
  87. }

De antemano, y muchísimas gracias