Why doesn’t the required attribute work?

Asked

Viewed 281 times

2

I have these two codes below, where Javascript does not allow enable the attribute required and I’ve tried many forms, but they have no effect. Someone has a solution for this?

/**
 * Captuar o elemento responsável por 
 * capturar o valor digitado pelo usuário
 */
const inputSearch = document.querySelector('input[name="q"]')

/**
 * Aplica um evento, do tipo "click", nos botões de pesquisa.
 * Para evitar incompatibilidades, você pode substituir o `forEach`
 * por um `for` "simples"
 */
document.querySelectorAll("#google-search, #wikipedia-search, #yahoo-search, #bing-search, #yandex-search, #duckduckgo, #archive-search, #ask-search, #aol-search, #Baidu-search, #infopedia-search, #wolframalpha-search, #cambio-search, #tempo-search, #dicionariopenal-search, #interpretacaocpp-search, #interpretacaocp-search")
  .forEach(btn => btn.addEventListener('click', search))

/**
 * Função responsável por identificar o botão pressionado,
 * e enviar o usuário para o site correto.
 *
 * @param {EventTarget} event
 * @return void
 */
function search(event) {
  event.preventDefault()

  const anchor = document.createElement('a')
  anchor.target = "_self"
  anchor.href = `${event.target.getAttribute('formaction')}${encodeURI(inputSearch.value)}`
  anchor.click()
}
<input type="text" class="col-sm-7" style="width:52%;height:44px;border: 1px solid #ebebeb;position: relative;top: 3px;background-color:#ffffff;" id="searchresultsquery" placeholder="Escreva o número do artigo do CPP e faça enter..." autofocus name="q" size="70" maxlength="70" required/>

<input type="image" id="dicionariopenal-search" style="width:45px;position: relative;left:0px;top:19px;" src="https://www.clubesorte.pt/corampopulo/c_elements/images/fotos/search-image1.png" alt="Submit Form" formaction="https://www.clubesorte.pt/corampopulo/login/interpretacao-cpp/palavras.php?letter=artigo ">
</form>

  • 1

    required only works with form Ubmit.

  • Meireles, besides the information provided by Augusto, you have actually used the required attribute incorrectly: simply declare (it’s like a Boolean), see an example here: https://www.w3schools.com/tags/att_input_required.asp

1 answer

3

As said by Augusto Vasques in your comment, the attribute required only perform the verification in the submission of the form. It is worth noting that after this validation, the event submit of a form is fired if all is valid.

Example of this behavior:

<form>
  <input required />
  <button type="submit">Enviar</button>
</form>

So among the thousands of things you can do to solve this problem, I will quote two:

Change the event click from the button to the submit form:

This seems to me the most semantically correct option, since what you are dealing with, in the end, is the submission of this small form. In addition, this way you can use the native validation of the browsers, since the event submit is triggered if the form is "valid". :)

const form = document.querySelector('form');
const nameField = form.querySelector('input');

form.addEventListener('submit', () => {
  const value = nameField.value;
  
  console.log(`Submetido: "${value}".`);
});
<form>
  <input required />
  <button type="submit">Enviar</button>
</form>

Validate the input within the Handler of the event click button:

Unlike the previous option, this does not seem so appropriate in the eyes of semantics, since the click is not as correct as a submit. But still, it’s an alternative.

const button = document.querySelector('button');
const nameField = document.querySelector('input');

button.addEventListener('click', (event) => {
  // Previne a submissão do formulário:
  event.preventDefault();

  const { value } = nameField;
  
  if (!value) {
    console.log('Complete os campos!');
    return;
  }
  
  console.log(`Submetido: "${value}".`);
});
<form>
  <input required />
  <button>Enviar</button>
</form>

  • I appreciate all your help but I actually tried everything and it doesn’t work because the js of origin nullifies all possibilities, but it is necessary for the working of the research that comes from the database. Perhaps there is a solution if the source js is changed?

  • 1

    What do you mean, "nullifies"? You could detail these factors a little more in your question?

  • It means that if I delete that js the required attribute already works, so... it is he who is determining some miscellaneous factor that nullifies all solutions because just delete it and everything works except the research that is most important.

Browser other questions tagged

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