How to add and remove required input with jQuery?

2

I have a select with two option , when I select the first option I want it to show me an input field strong> with the attribute and when I select the second option I want it to do the same, only removing the required input .

The function that I created adds the required in the input shown, but when I do it it shows the second input, it maintains the required in the two fields.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><html><headlang="pt-br">
<meta charset="utf-8">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script><scripttype="text/javascript">
$(document).ready(function(){
        $("#campos > input").hide();
        $("#formulario").change(function(){
                $("#campos > input").hide();
                $( '#'+$( this ).val() ).show('fast').attr('required', 'required');;
        });
});
</script>
</head>
<body>

        <select name="formulario" id="formulario">
                <option value="">--</option>
                <option value="empresa">Empresa</option>
                <option value="cantidato">Cantidato</option>
        </select>

        <div id="campos">
                <input type="text" value="" placeholder="CNPJ" id="empresa">
                <input type="text" value="" placeholder="CPF" id="cantidato">
        </div>
</body>
</html>

I would like the required to be kept only in the selected input.

Thank you.

    
asked by anonymous 26.11.2016 / 23:36

1 answer

3

You can use .attr() to change this attribute, like this:

$('select').on('change', function() {
    $('input').attr('required', this.value == 'req');
});

The .attr() has the following API: .attr(nomeDoAtributo, valorBooleano) . When the second parameter is true it adds the attribute, when false it removes the attribute.

jsFiddle: link

Edit:

I saw that you put your code to the question. An example could look like this:

$(document).ready(function() {
    $('#formulario').on('change', function() {
        var tipo = this.value;
        $('#empresa, #cantidato').each(function() {
            var usar = this.id == tipo;
            this.required = usar;
            this.style.display = usar ? 'block' : 'none';
        });
    });
});

jsFiddle: link

    
26.11.2016 / 23:41