javascript - Condtionally disable button by Radio and Checkbox -


i conditionally disable button based on radio , checkbox combination. radio have 2 options, first checked default. if user selects second option disable button until @ least 1 checkbox has been checked.

i have searched @ length on codepen , stack overflow cannot find solution works conditionals. results did find close couldn't adapt them needs javascript novice.

i using jquery, if helps.

if needed: http://codepen.io/traceofwind/pen/evnxzj

<form>  <div id="input-option1">first option: (required)     <input type="radio" name="required" id="required" value="1" checked="checked">yes     <input type="radio" name="required" id="required" value="2">no  <div>    <div id="input-option2">optionals:     <input type="checkbox" name="optionals" id="optionals" value="2a">optional 1     <input type="checkbox" name="optionals" id="optionals" value="2b">optional 2  <div>    <div id="input-option3">extras:     <input type="checkbox" name="extra" id="extra" value="3">extra 1  <div>       <button type="button" id="btn">add cart</button>  </form>

(please excuse code, in short hand example!)

the form element ids fixed. ids generated opencart believe naming convention set group, rather unique. cannot use ids such radio_id_1 , radio_id_2, example; opencart framework facet , not personal choice.

finally, in pseudo code hoping can suggest jquery / javascript solution along lines of:

if radio = '2'    if checkboxes = unchecked       btn = disabled       else          btn = enabled    end if end if 

here quick solution , hope that's after.

$(function() {     var $form = $("#form1");     var $btn = $form.find("#btn");     var $radios = $form.find(":radio");     var $checks = $form.find(":checkbox[name='optionals']");      $radios.add($checks).on("change", function() {          var radioval = $radios.filter(":checked").val();         $btn.prop("disabled", true);         if (radioval == 2) {             $btn.prop("disabled", !$checks.filter(":checked").length >= 1);         } else {             $btn.prop("disabled", !radioval);         }     }); }); 

here a demo above + html.

note: remove ids except form id, button id (since they're used in demo) can't have duplicate ids in html document. id meant identify unique piece of content. if idea style elements, use classes.


Comments