HTML 'required' attribute by Javascript

3

I'd like to know how to do that, when activeBtn was checked, ordenadorBanners got the required attribute, I tried the template below but it did not work, I'd like to know how to do it, and the " why "having to do it that 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>
    
asked by anonymous 01.08.2016 / 15:52

2 answers

6

You need to add an event handset to know when it is clicked or not.

And then you can use the .required property of the 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 so:

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

jsFiddle: link

Notes:

  • I did not use $ in the variable name because in JavaScript this is unusual. Just to name variables that are jQuery objects or other libraries
  • puts this code at the end of <body> or within a function that is called when the DOM is loaded and HTML is read.
01.08.2016 / 15:59
2

You can solve your problem like this:

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

<script type="text/javascript">
    checkedBtnAtiva();
    function checkedBtnAtiva(){
        var $activeBtn = document.getElementById('btn-ativa');
        var $ordenadorBanners = document.getElementById('ordem-banner');
        if ($activeBtn.checked) {
            $ordenadorBanners.required = true;
        }else{
            $ordenadorBanners.required = false;
        }
    }
</script>

Doing this way will get you checked if this checked or not even after you loaded the html . Remember that you must put script after html on which it will work. Preferably in footer . I hope I have helped.

    
01.08.2016 / 16:11