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

Confusion between commands.Bot and discord.Client | Which one should I use?

Whenever you look at YouTube tutorials or code from this website there is a real variation. Some developers use client = discord.Client(intents=intents) while the others use bot = commands.Bot(command_prefix="something", intents=intents) . Now I know slightly about the difference but I get errors from different places from my code when I use either of them and its confusing. Especially since there has a few changes over the years in discord.py it is hard to find the real difference. I tried sticking to discord.Client then I found that there are more features in commands.Bot . Then I found errors when using commands.Bot . An example of this is: When I try to use commands.Bot client = commands.Bot(command_prefix=">",intents=intents) async def load(): for filename in os.listdir("./Cogs"): if filename.endswith(".py"): client.load_extension(f"Cogs.{filename[:-3]}") The above doesnt giveany response from my Cogs ...

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

Where and how is this Laravel kernel constructor called? [closed]

Where and how is this Laravel kernel constructor called? public fucntion __construct(Application $app, $Router $roouter) { } I have read the documentation and some online tutorial but I can find any clear explanation. I am learning Laravel and I am wondering where does this kernel constructor receives its arguments from. "POSTMOTERM" CLARIFICATION: Here is more clarity.I have checked the boostrap/app.php and it is only used for boostrapping the interfaces into the container class. What is not clear to me is where and how the Kernel class is instatiated and the arguments passed to the object calling the constructor.Something similar to; obj = new kernel(arg1,arg2) or, is the framework using some magic functions somewhere? Special gratitude to those who burn their eyeballs and brain cells on this trivia before it goes into a full blown menopause alias "MARKED AS DUPLICATE". To some of the itchy-finger keyboard warriors, a.k.a The mods,because I believe in th...