0

JQuery newbie here.

I have a search form with about 16 fields, most of them are textboxes. rest of them are dropdowns. I have 3 radio buttons beneath these fields. When 1st one is selected, then some of the fields in the form should be disabled. When 2nd or 3rd radio option is selected, all fields should be enabled. I have the following code form this post. But it disables only two textboxes by its names. Anything better than this code?

Lets assume, the radio button names are option1, option2, option3.

Community
  • 1
  • 1
Kevin Rave
  • 13,876
  • 35
  • 109
  • 173
  • Please show a minimal representation of your HTML, and your implementation of the code from the linked answer, also: define 'better' in context of your use-case. – David Thomas Aug 29 '14 at 20:47

1 Answers1

1
$(":radio").change(function() {
    if ($(this).val() == "option1") {
        // When first button is selected, disable some fields
        $("#field1, #field2, #field3").prop('disabled', true);
    } else {
        // Otherwise enable the fields
        $("#field1, #field2, #field3").prop('disabled', false);
    }
});

Just add more fields to the selector to enable and disable all the appropriate fields.

Instead of listing all the IDs, you should give them a class in the HTML:

<input type="text" class="disable" name="whatever"/>

Then you can do:

$(".disable").prop('disabled', true);

to disable all the fields with class="disable" at once.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • What does `:radio` means? Any radio click on this page? – Kevin Rave Aug 29 '14 at 20:50
  • And, is there a better way / practice / standard to disable lot of fields instead of hardcoding them like in the else part? – Kevin Rave Aug 29 '14 at 20:51
  • It depends on what you're doing. Is there some rule for which fields should be enabled? Or maybe you could give them a class and use that. – Barmar Aug 29 '14 at 20:52
  • I guess, I got an answer for my radio question. – Kevin Rave Aug 29 '14 at 20:52
  • No specific rule. Just selecting one of the radios should disable them. What is the `could give them a class`? Can you point me some url to refer? – Kevin Rave Aug 29 '14 at 20:54
  • 1
    I've updated the answer. But surely the tutorial you learned jQuery from has examples of using class selectors, doesn't it? – Barmar Aug 29 '14 at 20:58
  • @KevinRave, in order for us to give you a more general answer, we'd have to know what HTML you have. – Jhecht Aug 29 '14 at 21:05