legolas Posted August 23, 2016 Share Posted August 23, 2016 I have a form with two radio buttons, line 1 and 2, and a text box on the third line <input type="radio" name="mybox1" value="1" checked="checked" />No <input type="radio" name="mybox2" value="2" />Yes <input type="text" size="8" name="mytext" /> The requirement is: If "No" is selected, the textbox must be empty on submitting the form. If "Yes" is selected, the textbox on line 3 must not be empty on submitting the form. So I cannot add the attribute 'required' in the third line, instead I have to control it dynamically depending on the radio button selection. How can I accomplish this? Link to comment Share on other sites More sharing options...
Ingolme Posted August 23, 2016 Share Posted August 23, 2016 You can use Javascript. Give each of the elements an ID, get a reference to those elements in Javascript using document.getElementById(). When either of the two radio buttons changes, set the textbox required property to true or false depending on which radio button is currently checked. Link to comment Share on other sites More sharing options...
dsonesuk Posted August 23, 2016 Share Posted August 23, 2016 Give radio buttons same attribute 'name' value, it will cause them to be part of group of buttons, with only one to show as being selected at one time, also you could use getElementsByName() instead then to check selected value and apply 'required'. Link to comment Share on other sites More sharing options...
legolas Posted August 25, 2016 Author Share Posted August 25, 2016 I got it to work now. One of the radiobuttons and the textbox needed each an id <input type="radio" name="mybox" value="1" id="mybox1" checked="checked" />No<input type="radio" name="mybox" value="2" />Yes<input type="text" size="8" name="mytext" id="mytext" /> On submitting the form <input type="submit" name="Submit" onClick='javascript:setRequired()' value="Submit" /> a Javascript was called function setRequired() { var s = document.getElementById("mybox1"); if (s.checked) { $("#mytext").removeAttr('required'); } else { $("#mytext").attr('required', ''); } } check for more details: http://stackoverflow.com/questions/18770369/how-to-set-html5-required-attribute-in-javascript Thanks for replies! Link to comment Share on other sites More sharing options...
Ingolme Posted August 25, 2016 Share Posted August 25, 2016 Yes, that's pretty much what I said. The "javascript:" prefix is not required in the onclick attribute. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now