Skip to main content

validate form inputs and enable button

What I need is to validate the form from the second section of the tab.

If there is any empty field of the 4 that does not appear hidden or transparent, the button should be disabled.

If they already have the 4 data, then the button is enabled.

The problem is that I add the two elements and for a reason the button is enabled since the last input has no data. And if I add a 3rd serious element, 6 fields to fill in or modify, because the data entry operator can proceed to delete an amount and the button should still be disabled even though the other 5 are filled with data the inputs are shoppingCartItemQuantity_ and price_.

How to make it take the inputs below the save button

Summary:

  1. Leave button visible when all inputs are filled with data
  2. Place focus on the input to fill the first one that is empty
const id_prod = document.querySelector('#first-tab >#articulos>#productos_content>.tr >.id_n').textContent;
console.log(id_prod)

const tbody = document.querySelector('#second-tab >.shoppingCartItemsContainer > #form2 >#tabla >.tbody')
function updateCantidadNuevo(input) {
  if(input.checkValidity()){
   input.setAttribute("data-oldvalue", input.value);
  }
  else{
    input.value = input.getAttribute("data-oldvalue") || input.min;
  }
}
function add(id, cantidad=1){
  let input = document.querySelector('#shoppingCartItemQuantity_'+id);
  input.value= input.valueAsNumber + cantidad;
  updateCantidadNuevo(input);
  
console.log(id,input);
}



const addToShoppingCartButtons = document.querySelectorAll('#first-tab > #articulos > tbody > tr > .td > .button')
console.log(addToShoppingCartButtons)
addToShoppingCartButtons.forEach((addToCartButton) => {
  addToCartButton.addEventListener('click', addToCartClicked);
  
  
  
  
  
  function addToCartClicked(event) {
  const button = event.target;
  
  const item = button.closest('.tr');

  const id_prod = item.querySelector('.id_n').textContent
  const cantidad_disponible = item.querySelector('.cantidad_disponible').textContent;
  const talla = item.querySelector('.talla').textContent;

  
  addItemToShoppingCart(id_prod,  cantidad_disponible, talla);
}
function addItemToShoppingCart(id_prod,cantidad_disponible,talla) {
    

  if(cantidad_disponible!=0){
  const elementsTitle = document.getElementsByClassName('title');

  for (let i = 0; i < elementsTitle.length; i++) {
    if (elementsTitle[i].innerText === id_prod) {
     
      return;
    }
  }

  const tr = document.createElement('tr')
    tr.classList.add('ItemCarrito')
     tr.setAttribute("id", `tr_${id_prod}`);

  Content = `
     <th scope="row">${id_prod}</th>

     <td class="table__productos">
     <input id="id_productos_${id_prod}" type="text" value="${id_prod}" class="id_productos"
    style="border: none; border-color: transparent;outline: 0;width: 40px;">

       <h6 id="title_${id_prod}" class="title" hidden>${id_prod}</h6>
     </td>

    
     <td class="table__cantidad_disponible">
     <input id="cantidad_disponible_${id_prod}" type="text" value="${cantidad_disponible}" class="cantidad_disponible"
     style="border: none; border-color: transparent;outline: 0;width: 40px;">
      
    </td>

    <td class="table__talla">
    <input id="talla_${id_prod}" type="text" value="${talla}" class="talla"
   style="border: none; border-color: transparent;outline: 0;width: 40px;">
      
     </td>

   



    
    
    <td class="table__cantidad">
                <input id="shoppingCartItemQuantity_${id_prod}" max="${cantidad_disponible}" oninput="updateCantidad(this)" class="shopping-cart-quantity-input shoppingCartItemQuantity_${id_prod}" type="number" onblur="habilitar()"
                    value="1" min="1">
                
                </td>
         <td class="table__precio">
     <input required id="precio_${id_prod}" type="text" class="precio"   onchange="CarritoTotalmio()" min="0"onblur="habilitar()">
      
     </td>

     <td class="table__delete">
     <button class="delete btn btn-danger">x</button>
      
    </td>
     `
   
    
   tr.innerHTML = Content 
     tbody.append(tr)
}else{
  console.log("tiene un 0 imposible agregar");
}
}


});

function habilitar() {
  let nombreApellido = document.getElementById("shoppingCartItemQuantity_"+id_prod);
  let email = document.getElementById("precio_"+id_prod);
 
  let enviarBoton = document.getElementById("guardardatos");

  if (nombreApellido.value === '' || email.value === '') {
    enviarBoton.disabled = true;
  } else {
    enviarBoton.disabled = false;
  }
}
input[type=number]::-webkit-inner-spin-button, 
input[type=number]::-webkit-outer-spin-button { 
  -webkit-appearance: none; 
  margin: 0; 
}
input[type=number] { -moz-appearance:textfield; }
<html>
<head>
    <title>Untitled-2</title>
  
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.8.0/css/bulma.min.css">
   
</head>
<body>



  

<section class="section">
      <div class="tabs">
         <ul class="tabs-menu">
          <li class="is-active" data-target="first-tab"><a>Tab one</a></li>
          <li data-target="second-tab"><a>Tab two</a></li>
        </ul>
      </div>
      <div class="tab-content" id="first-tab">

      <table id="articulos"class="table">
        <thead>
           
            <tr>
            
            <TH>id </TH>
            <TH>id del producto</TH>
            <TH>cantidad_disponible</TH>
            <TH>talla zapatos</TH>
                <TH>Añadir</TH>
              <TH>Añadir</TH>
            </tr>
        </thead>
        <tbody  id="productos_content">
             <tr class="tr">
         
            
            <td class="id_n">15<td>
            <td class="cantidad_disponible"> 3</td>
            <td class="talla"> 36</td>
              
<td class="td"><button id="15" onclick="add(15)"   class="button">Añadir</button></td>
  
        </tr> 
       
       <tr class="tr">
         
            
            <td class="id_n">1<td>
            <td class="cantidad_disponible"> 7</td>
            <td class="talla"> 40</td>
          
<td class="td"><button id="15" onclick="add(1)"   class="button">Añadir</button></td>
    
        </tr> 
        </tbody>
        </table>
    
          </div>



      <div class="tab-content" id="second-tab">
      <div class="shopping-cart-items shoppingCartItemsContainer">
      <form id="form2" action="javascript:habilitar()">

<input type="button" id="guardardatos" value="Guardar" onchange="habilitar()" disabled />
   

      <table id="tabla" class="table">
 
            <tr>
            <TH>id</TH>
            <TH>id del producto</TH>   
            <TH>cantidad_disponible</TH>
            <TH>talla zapatos</TH>          
            <TH>Añadir </TH>    
            </tr>
               <tbody id="carrito_content" class="tbody">
               
        </tbody>
    </table>

      <div class="float-right">
      Total:<input type="text" id="resultado_total" value="0" disabled > </input>

        </div>
    </form>
    </div>
    </div>
    </body>

<script>
    const tabSystem = {
    init(){
        document.querySelectorAll('.tabs-menu').forEach(tabMenu => {
            Array.from(tabMenu.children).forEach((child, ind) => {
                child.addEventListener('click', () => {
                    tabSystem.toggle(child.dataset.target);
                });
                if(child.className.includes('is-active')){
                    tabSystem.toggle(child.dataset.target);
                }
            });
        });
    },
    toggle(targetId){
        document.querySelectorAll('.tab-content').forEach(contentElement=>{
            contentElement.style.display = contentElement.id === targetId ? 'block' : 'none';
            document.querySelector(`[data-target="${contentElement.id}"]`).classList[contentElement.id === targetId ? 'add' : 'remove']('is-active');
        })
    },
};
// use it
tabSystem.init()
</script>


</html>

This is an example of how it should work.

My code to modify is the one above, that's the one that doesn't work

const form = [...document.querySelectorAll('.form__element-input')];
const boton = document.querySelector('#enviar');

form.forEach((input, index) => {
    boton.classList.add('none__send');
    input.addEventListener('input', () => {
        if (form.some(el => el.value.trim() === "")) {
            boton.classList.add('none__send');
        } else {
            boton.classList.remove('none__send');
        }
    })
});
.none__send {
  display:none;
}
<form method="post" class="form">
    <div class="form__title">
    </div>
    <div class="form__element">
        <input type="number" name="cedula" class="form__element-input"/>
    </div>
    <div class="form__element">
        <input type="number" name="telefono" class="form__element-input"/>
    </div>
    <div class="form__element">
        <input type="text" name="nombre" class="form__element-input"/>
    </div>
    <div class="form__button">
        <button type="submit" id="enviar">enviar</button>
    </div>
</form>
Via Active questions tagged javascript - Stack Overflow https://ift.tt/SH8OUAr

Comments

Popular posts from this blog

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console...

How to split a rinex file if I need 24 hours data

Trying to divide rinex file using the command gfzrnx but getting this error. While doing that getting this error msg 'gfzrnx' is not recognized as an internal or external command Trying to split rinex file using the command gfzrnx. also install'gfzrnx'. my doubt is I need to run this program in 'gfzrnx' or in 'cmdprompt'. I am expecting a rinex file with 24 hrs or 1 day data.I Have 48 hrs data in RINEX format. Please help me to solve this issue. source https://stackoverflow.com/questions/75385367/how-to-split-a-rinex-file-if-i-need-24-hours-data