0
 return $('#attending_day_1 input[type=radio]:checked').val() = " "

I want to check if returned value is empty/radio button is unchecked. This is not working, what am I missing?

alice
  • 101
  • 2
  • 11

3 Answers3

2

use this:

return $('#attending_day_1 input[type=radio]').is(":checked");
Hüseyin Cevizci
  • 919
  • 4
  • 17
  • Also if these are not checked? – alice Apr 30 '14 at 21:46
  • Yes, if your selector returns a single element. is(":checked") checks your radio button is checked or not. – Hüseyin Cevizci Apr 30 '14 at 21:48
  • If you have multiple radio buttons and want to check any of them is selected, you can use as: return $('#attending_day_1 input[type=radio]:checked').length> 0 ; – Hüseyin Cevizci Apr 30 '14 at 21:51
  • Please share your full code with jsfiddle. So I can understand the problem. – Hüseyin Cevizci Apr 30 '14 at 22:14
  • okay so I need to validate, by checking if any one of the two groups of radio buttons is checked. Error if nothing is selected. All of these scripts work here, but I am not successful when I use && operators. For example: return $('#attending_day_1 input[type=radio]:checked').length === 0 && $('#attending_day_2 input[type=radio]:checked').length === 0;} – alice Apr 30 '14 at 22:16
  • Thanks for the fiddle, I cannot use alert. I not to validate it by using depends? – alice Apr 30 '14 at 22:27
1

in javascript, = is assignment, == is a comparison operator. " " is a valid non empty string - try this:

'' === ' '

also, val() returns the value of the input element. if you want to check if none of the buttons are checked, see if the length of the jQuery selection is 0.

return ! $('#attending_day_1 input[type=radio]:checked').length

(note 0 is falsy, so !0 is true)

Gojko Adzic
  • 1,241
  • 10
  • 9
1

As a function, the line below will return true if there are no checkboxes selected:

return $('#attending_day_1 input[type=radio]:checked').length === 0;
Ishan Chatterjee
  • 825
  • 8
  • 21
  • return $('#attending_day_1 input[type=radio]:checked').length === 0 && $('#attending_day_2 input[type=radio]:checked').length === 0; can I do this as well? – alice Apr 30 '14 at 22:03
  • Yes you can, but it's a bit wordy (and a long line). Rather than do that, it would make sense to use a class selector (rather than two ID selectors). For example: http://jsfiddle.net/MH4H8/ – Ishan Chatterjee Apr 30 '14 at 23:36
  • Thanks a lot, I really like the class idea. But, I can't use alert. I need to show error on the page, can you show an example for displaying error when i validate rest of the page elements?. User has to select to come either on of the two days or both days. I display error if both days are unchecked. http://jsfiddle.net/pQNNU/ – alice May 01 '14 at 13:36