Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make a input field required if radio is checked

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 required to be filled per default. But if the user checks a radio button that is named "ladder" the "ladder-meters" field are required to be filled.

My input looks like this:

<input type="text" name="ladder-meters" id="ladder-meters">

and should like this at the onchange event on the radio

<input type="text" name="ladder-meters" id="ladder-meters" required>
like image 946
Morten Hagh Avatar asked Aug 15 '12 10:08

Morten Hagh


People also ask

How do I know if my input type radio is checked?

Using Input Radio checked property: The Input Radio checked property is used to return the checked status of an Input Radio Button. Use document. getElementById('id'). checked method to check whether the element with selected id is check or not.

How do you create an input element for a radio button?

To label a radio button, add a <label> element after the <input> element and insert a for attribute with the same value as the id of the associated <input> element. Then, write your label text in the <label> tag. While using <label> isn't strictly necessary, it's considered a best practice for two reasons.


1 Answers

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' />
like image 180
ColBeseder Avatar answered Oct 20 '22 04:10

ColBeseder