Не отправлять форму, если значение поля ввода равно указанному c тексту - PullRequest
0 голосов
/ 07 августа 2020

У меня есть форма с bootstrap и скриптом Google Apps. Я определил общую проверку для формы, но теперь мне нужно настроить проверку c для поля. Если поле ввода с идентификатором "estado" имеет значение "Terminado", форму не следует отправлять. Значение поля ввода генерируется функцией скрипта приложения Google и обновляется при изменении поля ввода «inputid».

Estado поля ввода определяется значением на «inputid». Когда я меняю значение inputid My script go на БД и получаю значение estado, как vlookup из excel. Затем, когда я меняю inputid Мой поиск кода или поиск значения в столбце estado базы данных.

Это мой код:

<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

    <title>Formulario Llegada</title>
  <?!=include("userformarrive-css");?>    
  </head>
  <body>
  
  <h4 align="center">Formulario de llegada</h4>
  
  <div class ="container">
   <form id = "userform">

<div class="form-row">
  <div class="form-group col-md-6">
    <label for="inputid">Identificador de viaje</label>
    <input type="text" class="form-control" id="inputid" required>
    <div class="invalid-feedback">
      No ha ingresado los datos o el viaje señalado ya se encuentra cerrado.
    </div>
  </div>
  <div class="form-group col-md-6">
    <label for="estado">Estado</label>
    <input type="text" class="form-control" id="estado" required disabled>
    <div class="invalid-feedback">
      No ha ingresado los datos o estos no son válidos.
    </div>
  </div>
</div>
       <button class="btn btn-primary" type="button" data-toggle="modal" data-target="#modal">Enviar datos</button>

    
  
  </div>
  </form>
  
  
  <!-- Acá van las notificaciones -->
  
  <div id="notifications">
  
  <div id="errornotification" class="toast" style="position: absolute; top: 0; right: 0;" role="alert" aria-live="assertive" aria-atomic="true" data-delay="5000">
  <div class="toast-header">
    <strong class="mr-auto">Error</strong>
    <small>Notificación</small>
    <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="toast-body">
    Uno o más campos requeridos no han sido completados dentro del formulario
  </div>
</div>
  
   <div id="successnotification"  class="toast" style="position: absolute; top: 0; right: 0;" role="alert" aria-live="assertive" aria-atomic="true" data-delay="5000">
  <div class="toast-header">
    <strong class="mr-auto">Datos correctos</strong>
    <small>Notificación</small>
    <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="toast-body">
    El formulario ha sido enviado de forma correcta. Recibirá un correo con el número de la operación ID para luego cerrar la llegada.
  </div>
</div>
    
  </div>
 
      <div id="loading" class="loading pt-40">
         <div class="d-flex justify-content-center">
         <div>
        
        <div class="spinner-border text-primary" style="width: 4rem; height: 4rem;"role="status">
        <span class="sr-only">Cargando</span>
        </div>
         <div> Cargando</div>
       </div>
      </div>
     
     </div>
     
<div id="modal" class="modal" tabindex="-1" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Envío de Formulario</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p>¿Desea enviar el registro?</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
        <button class="btn btn-outline-primary" id ="enviar" >Registrar Salida</button>
      </div>
    </div>
  </div>
</div>  




var arrayOfValues;

function afterButtonClicked() {

  if (validate()) {

    var cuenta = document.getElementById("cuenta");
    var inputid = document.getElementById("inputid");
    var estado = document.getElementById("estado");
    var kmfinal = document.getElementById("kmfinal");

    var rowDataarrive = {
      cuenta: cuenta.value,
      inputid: inputid.value,
      estado: estado.value,
      kmfinal: kmfinal.value,
    };

    google.script.run.addNewRowarrive(rowDataarrive);
    $('#modal').modal('hide')
    $('#successnotification').toast('show')
    setTimeout(function () {
      location.reload()
    }, 6000);
  } else {
    $('#modal').modal('hide')
    $('#errornotification').toast('show')
  }
}

function validate() {
  var fieldsToValidate = document.querySelectorAll("#userform input, #userform select");
  Array.prototype.forEach.call(fieldsToValidate, function (el) {
    if (el.checkValidity()) {
      el.classList.remove("is-invalid");
    } else {
      el.classList.add("is-invalid");
    }
  });

  return Array.prototype.every.call(fieldsToValidate, function (el) {
    return el.checkValidity();
  });
}

function getId() {
  var idCode = document.getElementById("inputid").value;
  google.script.run.withSuccessHandler(updateIdcode).getId(idCode);
}

function updateIdcode(estadolist) {
  document.getElementById("estado").value = estadolist;
}

google.script.url.getLocation(function (location) {
  document.getElementById("inputid").value =
    location.parameters.inputid[0];
  getId();
});

document.getElementById("inputid").addEventListener("input", getId);
document.getElementById("enviar").addEventListener("click", afterButtonClicked);
document.getElementById("loading").remove();

Теперь я попробовал много способов настроить валидацию указанного c поля ввода, но ничего не работало. Я попытался установить значение «пусто», если входное значение имело значение «Терминадо» с функцией, и воспользоваться моей общей проверкой, но это не сработало. У вас есть идея решить мою проблему?

Ответы [ 2 ]

2 голосов
/ 07 августа 2020

Как @Fritzdultimate сказал, что вам, вероятно, нужно использовать event.preventDefault(), но я думаю, что есть проблема и с вашей функцией проверки.

function validate() {
  var fieldsToValidate = document.querySelectorAll("#userform input, #userform select");
  Array.prototype.forEach.call(fieldsToValidate, function (el) {
    if (el.checkValidity()) {
      el.classList.remove("is-invalid");
    } else {
      el.classList.add("is-invalid");
    }
  });

  return Array.prototype.every.call(fieldsToValidate, function (el) {
    return el.checkValidity();
  });
}

Вместо Array.prototype вы должны иметь фактический массив, который вы хотите чтобы запустить функцию следующим образом:

function validate() {
  var fieldsToValidate = document.querySelectorAll("#userform input, #userform select");
  fieldsToValidate.forEach(function (el) {
    if (el.checkValidity()) {
      el.classList.remove("is-invalid");
    } else {
      el.classList.add("is-invalid");
    }
  });

  return fieldsToValidate.every(function (el) {
    return el.checkValidity();
  });
}

Изменить: @dwmorrin верен, fieldsToValidate.forEach(function (el) { совпадает с Array.prototype.forEach.call(fieldsToValidate, function (el) {, так что это не должно иметь значения.

0 голосов
/ 11 августа 2020

Я нашел решение, вызывающее в первом экземпляре проверку спецификаций c, и, если возвращает true, переходит ко второй проверке, это код javascript:

var arrayOfValues;


function buttonClickAction(){
var isValid = document.getElementById("estado").value
if(isValid == 1){

$('#errornotificationestado').toast('show')
$('#modal').modal('hide')

isValid.classList.add("is-invalid")

}else {

afterButtonClicked()

}
}


function afterButtonClicked(){

if(validates()){


var cuenta = document.getElementById("cuenta");   
var inputid = document.getElementById("inputid");
var estado = document.getElementById("estado");
var kmfinal = document.getElementById("kmfinal");


    
var rowDataarrive = {cuenta: cuenta.value,inputid:inputid.value,
               estado: estado.value,kmfinal:kmfinal.value,
                          
               };
     
             
               
google.script.run.addNewRowarrive(rowDataarrive);
$('#modal').modal('hide')
$('#successnotification').toast('show')
setTimeout(function(){location.reload()}, 6000);
} else{
$('#modal').modal('hide')
$('#errornotification').toast('show')
}
}

function validates(){

var fieldsToValidate = document.querySelectorAll("#userform input, #userform select");
Array.prototype.forEach.call(fieldsToValidate, function(el){
if(el.checkValidity()){
el.classList.remove("is-invalid");

}else{
el.classList.add("is-invalid");


}
   
});

return Array.prototype.every.call(fieldsToValidate, function(el){
return el.checkValidity();

});

}
function getId(){

var idCode = document.getElementById("inputid").value;

google.script.run.withSuccessHandler(updateIdcode).getId(idCode);

}

function updateIdcode(estadolist){
document.getElementById("estado").value = estadolist; 

}
 
google.script.url.getLocation(function(location) {
document.getElementById("inputid").value = location.parameters.inputid[0];
getId(); 
});
     
document.getElementById("inputid").addEventListener("input",getId);
document.getElementById("enviar").addEventListener("click",buttonClickAction);
document.getElementById("loading").remove();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...