Jump to content

validate html5 form


legolas

Recommended Posts

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

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

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

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...