Search code examples
javascriptjquerycsstoggleformidable

formidable toggle switch, how to click the label?


Currently, the below HTML code only switches when you click the input (ie. the center switch). I need the switch to happen when you click the labels (ie. Yes or No). How to make that happen?

        <div>
            <span class="frm_off_label frm_switch_opt">No</span>
            <label class="frm_switch">
                   <input type="checkbox" name="2002" id="field_2002" value="Yes" checked="checked" 
                            data-off="No" data-sectionid="2002" data-frmval="Yes" placeholder="Yes">
                  <span class="frm_slider"></span>
              </label>
               <span class="frm_on_label frm_switch_opt">Yes</span>
         </div>

What are the ways to make the click of Yes or No, do the same thing as clicking the input?


Solution

  • You can achieve this by setting the checked status of input -

    HTML

       <div>
            <span class="frm_off_label frm_switch_opt">No</span>
            <label class="frm_switch">
                   <input type="checkbox" name="2002" id="field_2002" value="Yes" checked="checked" 
                            data-off="No" data-sectionid="2002" data-frmval="Yes" placeholder="Yes">
                  <span class="frm_slider"></span>
              </label>
               <span class="frm_on_label frm_switch_opt">Yes</span>
         </div>
    

    JS (with jquery)

    $('.frm_off_label').on('click', function(){
            $(this).next('label').find("input")[0].checked = false;
    });
    
    
    $('.frm_on_label').on('click', function(){
            $(this).prev('label').find("input")[0].checked = true;
    });
    

    CSS (optioanl)

    .frm_switch_opt{
      cursor:pointer;
    }
    

    You can see it in action on jsfiddle

    https://jsfiddle.net/guruling/tegmps9b/27/