Conditional Display in Javascript

Asked

Viewed 80 times

2

Good afternoon guys, I have an expense code, I want an input form called "number kilometer" with display:one to appear only if in the expense field, is selected "Mileage". I removed the code to be more synthesized select options.

<select name="tipoDespesa" required style="margin-left:50px;">
  \*várias opções aqui*\
</select>

<input type="number" name="numeroKm" placeholder="KM" id="km" step=".1" style="display: none; height: 30px;width: 70;padding-left: 10px;">
<input type="number" name="precoDespesa" placeholder="R$" id="valor" step=".01" required placeholder="Insira um valor!">

<script>
  let ehQuilometragem = document.getElementsByName("tipoDespesa")[0]
  if (ehQuilometragem == "Quilometragem"){
    function adicionaCampoKm(){
      $("#km").Show();
    }
  adicionaCampoKm()
};
</script>

I tried this script at the end but apparently did not get results.

1 answer

2


You are mixing jQuery with Javascript(Vanilla) no need, this is very simple to do, follow an example I made with if/Else, but, in fact it would be possible to leave in a line only using ternary condition:

$(() => {
  let select = $('[name=tipoDespesa]');
  let inptKm = $('#km');
  
  select.on('change', () => {
    if(select.val() == 'Quilometragem') inptKm.show()
    else inptKm.hide()
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select name="tipoDespesa" required style="margin-left:50px;">
  <option value="coisa">Uma coisa</option>
  <option value="outra">Outra coisa</option>
  <option value="Quilometragem">Quilometragem</option>
</select>

<input type="number" name="numeroKm" placeholder="KM" id="km" step=".1" style="display: none; height: 30px;width: 70;padding-left: 10px;">
<input type="number" name="precoDespesa" placeholder="R$" id="valor" step=".01" required placeholder="Insira um valor!">

Just one example using ternary:

$(() => {
  let select = $('[name=tipoDespesa]');
  let inptKm = $('#km');

  select.on('change', () => {
    select.val() == 'Quilometragem' ? inptKm.show() : inptKm.hide()
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select name="tipoDespesa" required style="margin-left:50px;">
  <option value="coisa">Uma coisa</option>
  <option value="outra">Outra coisa</option>
  <option value="Quilometragem">Quilometragem</option>
</select>

<input type="number" name="numeroKm" placeholder="KM" id="km" step=".1" style="display: none; height: 30px;width: 70;padding-left: 10px;">
<input type="number" name="precoDespesa" placeholder="R$" id="valor" step=".01" required placeholder="Insira um valor!">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.