简体   繁体   中英

How to correct validate based on choice of radio button?

I have a validation scenario where I have two radio buttons. I then Have two input text fields.

If the first radio button is selected the user only has to enter data in the first field. If the second radio button is select the user has to enter data in the first field and a date in the second field.

Now the first radio button is selected by default when the page loads. If the user does not enter anything in the first field with either button selected then there is a validation error that occurs onsubmit.

Now if the second radio button is selected and the user enters data in the first field and does not enter the date in the second field then the validation error occurs.

The problem I am having is that when the first button is selected if the user enters data in the first field but does not enter a date in the second field a validation error is occurring. This should not happen. The only way a validation error should occur if the first button is selected is if incorrect data is entered into the first field or if no data is entered into the first field. The user is not required to enter a date in the second field. So how can I write the JavaScript to reflect these conditions?

Here is the link to jsfiddle: http://jsfiddle.net/rnnzn/

That's a lot in fiddle, and it doesn't seem to work in there.

I think that you think radio inputs work differently than they do. Don't check the value of the name of the control, check if the particular radio is checked.

ex:

if(document.getElementById('myform').radioName[0].checked){
  //validate based on first radio selection
}eles{
  //validate based on second radio selection
}

The important part to remember is that radio's and checkboxes are arrays, they are not as easy to deal with as text and select inputs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM