make a input field required if radio is checked

前端 未结 3 1174
礼貌的吻别
礼貌的吻别 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

    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:

    
    

提交回复
热议问题