Run a function when an option is selected on dropdown

Hello. Basically what I’m trying to do is to show other text fields when the option selected from a dropdown is “Yes” (Sí). If the option selected is any other than “Yes” then the other inputs should hide. Can’t get it to work. Can someone help me understand why this is? What am I doing wrong? And ideally explain why, in a simple way?

Thanks all!

The code is this:

<script>
  var showAll = document.getElementById("requieres-factura");
  showAll.addEventListener("change", muestra);

  function muestra() {
    if (showAll.value === "Yes") {
      document.getElementById('razon-social').disabled = false;
      document.getElementById('rfc').disabled = false;
      document.getElementById('uso-del-cfdi').disabled = false;
      document.getElementById('div_factura').style.display = 'block';
    } else {
      document.getElementById('razon-social').disabled = true;
      document.getElementById('rfc').disabled = true;
      document.getElementById('uso-del-cfdi').disabled = true;
      document.getElementById('div_factura').style.display = 'none';
    }
  }

</script>
<p class="cart-attribute__field">
  <label>¿Requieres factura?</label><br>
  <select required class="required" id="requieres-factura" name="attributes[¿Requieres factura?]">
            <option value="Elige una opción"{% if cart.attributes["¿Requieres factura?"] == "Elige una opción" %} selected{% endif %}>Elige una opción</option>
            <option value="Yes"{% if cart.attributes["¿Requieres factura?"] == "Sí" %} selected{% endif %}>Sí</option>
            <option value="No (No se realizaran facturas posteriores sin excepción)"{% if cart.attributes["¿Requieres factura?"] == "No (No se realizaran facturas posteriores sin excepción)" %} selected{% endif %}>No (No se realizaran facturas posteriores sin excepción)</option>
          </select>
</p>
<div id=div_factura style="display: none">
  <p class="cart-attribute__field">
    <label for="razon-social">Razón Social</label>
    <input id="razon-social" type="text" name="attributes[Razón Social]" value="">
  </p>
  <p class="cart-attribute__field">
    <label for="rfc">RFC</label>
    <input id="rfc" type="text" name="attributes[RFC]" value="">
  </p>
  <p class="cart-attribute__field">
    <label>Uso del CFDI</label><br>
    <select id="uso-del-cfdi" name="attributes[Uso del CFDI]">
    <option value="G01	Adquisición de mercancias"{% if cart.attributes["Uso del CFDI"] == "G01	Adquisición de mercancias" %} selected{% endif %}>G01	Adquisición de mercancias</option>
    <option value="G02	Devoluciones descuentos o bonificaciones"{% if cart.attributes["Uso del CFDI"] == "G02	Devoluciones descuentos o bonificaciones" %} selected{% endif %}>G02	Devoluciones, descuentos o bonificaciones</option>
    <option value="G03	Gastos en general"{% if cart.attributes["Uso del CFDI"] == "G03	Gastos en general" %} selected{% endif %}>G03	Gastos en general</option>
    <option value="I01	Construcciones"{% if cart.attributes["Uso del CFDI"] == "I01	Construcciones" %} selected{% endif %}>I01	Construcciones</option>
    <option value="I02	Mobilario y equipo de oficina por inversiones"{% if cart.attributes["Uso del CFDI"] == "I02	Mobilario y equipo de oficina por inversiones" %} selected{% endif %}>I02	Mobilario y equipo de oficina por inversiones</option>
    <option value="I03	Equipo de transporte"{% if cart.attributes["Uso del CFDI"] == "I03	Equipo de transporte" %} selected{% endif %}>I03	Equipo de transporte</option>
    <option value="I04	Equipo de computo y accesorios"{% if cart.attributes["Uso del CFDI"] == "I04	Equipo de computo y accesorios" %} selected{% endif %}>I04	Equipo de computo y accesorios</option>
    <option value="I05	Dados troqueles moldes matrices y herramental"{% if cart.attributes["Uso del CFDI"] == "I05	Dados troqueles moldes matrices y herramental" %} selected{% endif %}>I05	Dados, troqueles, moldes, matrices y herramental</option>
    <option value="I06	Comunicaciones telefónicas"{% if cart.attributes["Uso del CFDI"] == "I06	Comunicaciones telefónicas" %} selected{% endif %}>I06	Comunicaciones telefónicas</option>
    <option value="I07	Comunicaciones satelitales"{% if cart.attributes["Uso del CFDI"] == "I07	Comunicaciones satelitales" %} selected{% endif %}>I07	Comunicaciones satelitales</option>
    <option value="I08	Otra maquinaria y equipo"{% if cart.attributes["Uso del CFDI"] == "I08	Otra maquinaria y equipo" %} selected{% endif %}>I08	Otra maquinaria y equipo</option>
    <option value="D01	Honorarios médicos dentales y gastos hospitalarios"{% if cart.attributes["Uso del CFDI"] == "D01	Honorarios médicos dentales y gastos hospitalarios" %} selected{% endif %}>D01	Honorarios médicos, dentales y gastos hospitalarios</option>
    <option value="D02	Gastos médicos por incapacidad o discapacidad"{% if cart.attributes["Uso del CFDI"] == "D02	Gastos médicos por incapacidad o discapacidad" %} selected{% endif %}>D02	Gastos médicos por incapacidad o discapacidad</option>
    <option value="D03	Gastos funerales"{% if cart.attributes["Uso del CFDI"] == "D03	Gastos funerales" %} selected{% endif %}>D03	Gastos funerales</option>
    <option value="D04	Donativos"{% if cart.attributes["Uso del CFDI"] == "D04	Donativos" %} selected{% endif %}>D04	Donativos</option>
    <option value="D05	Intereses reales efectivamente pagados por créditos hipotecarios (casa habitación)"{% if cart.attributes["Uso del CFDI"] == "D05	Intereses reales efectivamente pagados por créditos hipotecarios (casa habitación)" %} selected{% endif %}>D05	Intereses reales efectivamente pagados por créditos hipotecarios (casa habitación)</option>
    <option value="D06	Aportaciones voluntarias al SAR"{% if cart.attributes["Uso del CFDI"] == "D06	Aportaciones voluntarias al SAR" %} selected{% endif %}>D06	Aportaciones voluntarias al SAR</option>
    <option value="D07	Primas por seguros de gastos médicos"{% if cart.attributes["Uso del CFDI"] == "D07	Primas por seguros de gastos médicos" %} selected{% endif %}>D07	Primas por seguros de gastos médicos</option>
    <option value="D08	Gastos de transportación escolar obligatoria"{% if cart.attributes["Uso del CFDI"] == "D08	Gastos de transportación escolar obligatoria" %} selected{% endif %}>D08	Gastos de transportación escolar obligatoria</option>
    <option value="D09	Depósitos en cuentas para el ahorro primas que tengan como base planes de pensiones"{% if cart.attributes["Uso del CFDI"] == "D09	Depósitos en cuentas para el ahorro primas que tengan como base planes de pensiones" %} selected{% endif %}>D09	Depósitos en cuentas para el ahorro, primas que tengan como base planes de pensiones</option>
    <option value="D10	Pagos por servicios educativos (colegiaturas)"{% if cart.attributes["Uso del CFDI"] == "D10	Pagos por servicios educativos (colegiaturas)" %} selected{% endif %}>D10	Pagos por servicios educativos (colegiaturas)</option>
    <option value="P01	Por definir"{% if cart.attributes["Uso del CFDI"] == "P01	Por definir" %} selected{% endif %}>P01	Por definir</option>
  </select>
  </p>
</div>

Hi,

If you move the JavaScript to after the HTML it should work. Like this:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Some title</title>
  </head>

  <body>
    <p class="cart-attribute__field"><label>¿Requieres factura?</label><br>
    <select class="required" id="requieres-factura" name="attributes[¿Requieres factura?]" required="">
      <option value="Elige una opción">
        Elige una opción
      </option>
      <option value="Yes">
        Sí
      </option>
      <option value="No (No se realizaran facturas posteriores sin excepción)">
        No (No se realizaran facturas posteriores sin excepción)
      </option>
    </select></p>
    <div id="div_factura" style="display: none">
      <p class="cart-attribute__field"><label for="razon-social">Razón Social</label> <input id="razon-social" name="attributes[Razón Social]" type="text" value=""></p>
      <p class="cart-attribute__field"><label for="rfc">RFC</label> <input id="rfc" name="attributes[RFC]" type="text" value=""></p>
      <p class="cart-attribute__field"><label>Uso del CFDI</label><br>
      <select id="uso-del-cfdi" name="attributes[Uso del CFDI]">
        <option value="G01 Adquisición de mercancias">
          G01 Adquisición de mercancias
        </option>
        <option value="G02 Devoluciones descuentos o bonificaciones">
          G02 Devoluciones, descuentos o bonificaciones
        </option>
        <option value="G03 Gastos en general">
          G03 Gastos en general
        </option>
        <option value="I01 Construcciones">
          I01 Construcciones
        </option>
        <option value="I02 Mobilario y equipo de oficina por inversiones">
          I02 Mobilario y equipo de oficina por inversiones
        </option>
        <option value="I03 Equipo de transporte">
          I03 Equipo de transporte
        </option>
        <option value="I04 Equipo de computo y accesorios">
          I04 Equipo de computo y accesorios
        </option>
        <option value="I05 Dados troqueles moldes matrices y herramental">
          I05 Dados, troqueles, moldes, matrices y herramental
        </option>
        <option value="I06 Comunicaciones telefónicas">
          I06 Comunicaciones telefónicas
        </option>
        <option value="I07 Comunicaciones satelitales">
          I07 Comunicaciones satelitales
        </option>
        <option value="I08 Otra maquinaria y equipo">
          I08 Otra maquinaria y equipo
        </option>
        <option value="D01 Honorarios médicos dentales y gastos hospitalarios">
          D01 Honorarios médicos, dentales y gastos hospitalarios
        </option>
        <option value="D02 Gastos médicos por incapacidad o discapacidad">
          D02 Gastos médicos por incapacidad o discapacidad
        </option>
        <option value="D03 Gastos funerales">
          D03 Gastos funerales
        </option>
        <option value="D04 Donativos">
          D04 Donativos
        </option>
        <option value="D05 Intereses reales efectivamente pagados por créditos hipotecarios (casa habitación)">
          D05 Intereses reales efectivamente pagados por créditos hipotecarios (casa habitación)
        </option>
        <option value="D06 Aportaciones voluntarias al SAR">
          D06 Aportaciones voluntarias al SAR
        </option>
        <option value="D07 Primas por seguros de gastos médicos">
          D07 Primas por seguros de gastos médicos
        </option>
        <option value="D08 Gastos de transportación escolar obligatoria">
          D08 Gastos de transportación escolar obligatoria
        </option>
        <option value="D09 Depósitos en cuentas para el ahorro primas que tengan como base planes de pensiones">
          D09 Depósitos en cuentas para el ahorro, primas que tengan como base planes de pensiones
        </option>
        <option value="D10 Pagos por servicios educativos (colegiaturas)">
          D10 Pagos por servicios educativos (colegiaturas)
        </option>
        <option value="P01 Por definir">
          P01 Por definir
        </option>
      </select></p>
    </div>

    <script>
      var showAll = document.getElementById("requieres-factura");
      showAll.addEventListener("change", muestra);

      function muestra() {
        if (showAll.value === "Yes") {
          document.getElementById('razon-social').disabled = false;
          document.getElementById('rfc').disabled = false;
          document.getElementById('uso-del-cfdi').disabled = false;
          document.getElementById('div_factura').style.display = 'block';
        } else {
          document.getElementById('razon-social').disabled = true;
          document.getElementById('rfc').disabled = true;
          document.getElementById('uso-del-cfdi').disabled = true;
          document.getElementById('div_factura').style.display = 'none';
        }
      }
    </script>
  </body>
</html>

The reason that it won’t work the other way round is that you are trying to manipulate elements in the DOM before they are present.

[quote=“James_Hibbard, post:2, topic:297388”]

Thanks so much for your reply. I changed the position and it’s still not working. You can see the site here: https://ninjanutzstudio.myshopify.com/cart

When you selected “Sí” (yes) it doesn’t show the rest of the inputs.

Thanks for your help.

Oh, sorry, I think it’s working now. :stuck_out_tongue:

Thanks so much for your help!!

1 Like

Just a question about the code. How would I make it so that if the selection is YES in the first dropdown, then the rest of the fields now become required and if the selection to the first dropdown is NO, then the fields are not required anymore?

Thanks so much.

I think I got it working. For anyone who may need this:

I set the inputs to be required and disabled, like so:

<p class="cart-attribute__field">
    <label for="razon-social">Razón Social</label>
    <input id="razon-social" type="text" name="attributes[Razón Social]" value="" required disabled>
  </p>
  <p class="cart-attribute__field">
    <label for="rfc">RFC</label>
    <input id="rfc" type="text" name="attributes[RFC]" value="" required disabled>
  </p>

That way the initial state is for the input to be disabled and only when the first dropdown is set to YES, then it becomes enabled and then the required also is enabled.

Hope this makes sense, and I would like if someone confirms this for me, just to be sure it’s the right way to do it.

Thanks!

1 Like

New update: This code is used in a shopping store. It looks like this:

The question is now, how can I make sure that if the option selected in the dropdown is “Elige una opcion” (Choose an option) then people are not able to go to the checkout? They either have to pick YES or NO to proceed.

Thanks for your help!!!

Hi,
If you remove the value from that option it will nullify it, that will force them to pick yes or no.

The browser will produce a red border if the option with an empty value is selected, that alerts the user to select a valid option.

    <select class="required" id="requieres-factura" name="attributes[¿Requieres factura?]" required="">
      <option value=""> <!--remove value to negate option-->
        Elige una opción
      </option>
      <option value="Yes">
        Sí
      </option>
      <option value="No (No se realizaran facturas posteriores sin excepción)">
        No (No se realizaran facturas posteriores sin excepción)
      </option>
    </select>
1 Like

This totally worked. Thanks SO MUCH!!

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.