make a input field required if radio is checked

前端 未结 3 1155
礼貌的吻别
礼貌的吻别 2021-01-01 23:53

Can I somehow insert the required attribute into an input field only if a certain radio is checked?

I have an input field named \"ladder-meters\" that is not require

相关标签:
3条回答
  • 2021-01-01 23:58

    Easy to achieve with jQuery:

    $('#ladder').change(function () {
        if($(this).is(':checked') {
            $('#ladder-meters').attr('required');
        } else {
            $('#ladder-meters').removeAttr('required');
        }
    });
    
    0 讨论(0)
  • 2021-01-01 23:58
    document.getElementById("ladder").addEventListener('change', function(){
        document.getElementById("ladder-meters").required = this.checked ;
    })
    

    Whenever the checkbox is clicked, the required attribute will be changed to match the checked attribute of the checkbox. To reverse this relationship, replace this.checked with !this.checked

    This may need some adjustment to suit your specific project.

    This will work with this checkbox:

    <input type='checkbox' id='ladder' name='ladder' />
    
    0 讨论(0)
  • 2021-01-02 00:15

    Tried F. Orvalho, didn't work for me, I had to use

    $('#ladder').change(function () {
        if(this.checked) {
            $('#ladder-meters').prop('required', true);
        } else {
            $('#ladder-meters').prop('required', false);
        }
    });
    

    It could be usefull. Thx to F. Orvalho for the structure

    0 讨论(0)
提交回复
热议问题