Select option makes the Input field mandatory

Asked

Viewed 435 times

-2

I wonder if I can make a document attachment input mandatory depending on the select option.

I looked at some questions / related articles and could not find what I was looking for.

HTML code:

<div class="control-form col-md-6">
    <label class="control-label">Motivo da Exclusão/Bloqueio</label>
    <select class="form-control col-md-12 obrigatorio" name="motivo_select" id="motivo_select">
        <option value="1"></option>
        <option value="2">Dois</option>
        <option value="3">Tres</option>
        <option value="4">Quatro</option>
        <option value="5">Cinco</option>
        <option value="6">Seis</option>
        <option value="7">Sete</option>
    </select>
</div> 
<div class="col-md-6"> 
    <label class="control-label" for="codigo">Anexar Confissão</label> 
    <input type="hidden" id="confissao_status" name="confissao_status" class="form-control input-sm status-anexo" readonly> 
    <div class="input-group">
       <input type="text" id="confissao" name="confissao" class="form-control input-sm obg-anx" readonly> 
        <div class="input-group-addon border-left-none" onclick="showCamera2('CONFISSÃO DE DÍVIDA', this)">
            <span class="fluigicon fluigicon-paperclip"></span>
        </div>       
    </div>
</div> 

Javascript code:

$('#motivo_select').change(function() {
    if ($('#motivo_select').val() == '4') {
        $(".obg-anx").each(function() {
            if (!$(this).hasClass("opcional")) {
                if ($(this).val() == "") {
                    contador++;
                    $(this).addClass("error");
                }
            }
        });
    }
});

1 answer

1

You can add an event to the form to intercept Submit and apply a validation. It’s a very simple and fast option:

const form = document.querySelector('#myForm');
form.addEventListener('submit', function() {
    event.preventDefault();
    const mySelectValue = document.querySelector('#mySelect').value;
    if (mySelectValue === '3') {
        // Obrigatório selecionar um arquivo:
        if (document.querySelector('#myFile').files.length === 0) {
            alert('Selecione um arquivo');
            return;
        }
    }
    
    console.log('post');
    // return true;
});
<form id="myForm">
  <select id="mySelect">
    <option value="1">Opção 1</option>
    <option value="2">Opção 2</option>
    <option value="3">Opção 3</option>
  </select>
  <input type="file" id="myFile" />
  <input type="submit" value="postar" />
</form>

Browser other questions tagged

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