Atributo ‘required’ do HTML pelo Javascript

Question:

I wonder how do I get when activeBtn were checked, the ordenadorBanners won the attribute required , I tried the following model did not work, I would like to know how to do this, and the "why" of having to do it in such a way.

var $activeBtn = document.getElementById('btn-ativa');
var $ordenadorBanners = document.getElementById('ordem-banner');

if ($activeBtn.checked) {
   $ordenadorBanners.required = true;
}

<form>
    <fieldset>
        <input type="number" name="" min="1" max="10" id="ordem-banner" pattern="">
        <label class="switch">
            <input type="checkbox" id="btn-ativa">
            <div class="slider round"></div>
            </label>
    </fieldset>
    <fieldset>
        <input type="submit" name="" value="Cadastrar">
    </fieldset>
</form>

Answer:

You have to add an event headphone to know when it's clicked or not.

And then you can use the property .required element or set directly in HTML with setAttribute .

Example:

var activeBtn = document.getElementById('btn-ativa');
var ordenadorBanners = document.getElementById('ordem-banner');
activeBtn.addEventListener('change', function() {
    ordenadorBanners.required = this.checked;
});

Or like this:

if (this.checked) ordenadorBanners.setAttribute('required', 'required');
else ordenadorBanners.removeAttribute('required', 'required');

jsfiddle: https://jsfiddle.net/9y7282dg/


Grades:

  • I didn't use the $ in the name of the variables because in JavaScript this is not usual. Just to name variables that are jQuery objects or objects from other libraries
  • places this code at the end of the <body> or inside a function that is called when the DOM is loaded and the HTML read.
Scroll to Top