Results 1 to 3 of 3

Thread: Javascript: Check and Uncheck a checkbox based on select option

  1. #1
    Jami's Avatar
    Join Date
    Jan 2002
    Posts
    225
    Rep Power
    16

    Javascript: Check and Uncheck a checkbox based on select option

    Hello all,

    I have the following
    HTML Code:
    <select name="period" id="showhide">
               <option class="a" selected="selected">One Time Only</option> 
    	   <option class="b" value="m1">Monthly Billing</option>
    	   <option class="b" value="y3">Quarterly Billing</option>
    	   <option class="b" value="y1">Billed Annually</option>
    </select>
    If class="a" I want the checkbox unchecked
    If class="b" I want it checked

    HTML Code:
    <input type="checkbox" name="recurring" value="">
    I'm using the class= to show and hide other form elements on the page, and that part works great. So I'm hoping I can use them to automatically set my checkbox based on a persons selection.

    Your help is much appreciated.

  2. #2
    Thinkin' out loud again Builder's Avatar
    Join Date
    Nov 2002
    Location
    Illinois
    Posts
    2,088
    Rep Power
    19
    Haven't tested it, but this should come close to working:

    HTML Code:
    <select name="period" id="showhide" onchange="check(this)" >
               <option class="a" selected="selected">One Time Only</option> 
    	   <option class="b" value="m1">Monthly Billing</option>
    	   <option class="b" value="y3">Quarterly Billing</option>
    	   <option class="b" value="y1">Billed Annually</option>
    </select>
    
    <input type="checkbox" name="recurring" id="recurring" value="" />
    And the JavaScript code:
    Code:
    function check(el){
       if ((el.value == 'm1') || (el.value == 'y3') || (el.value == 'y1')) {
         document.getElementById('recurring').checked=true;
       }
       else{
         document.getElementById('recurring').checked=false;
       }
    }
    The JS would be a tad simpler if you had a value attribute for your "One Time Only" option, even if was just value="". The Javascript would then be:
    Code:
    function check(el){
       if (el.value == '') {
         document.getElementById('recurring').checked=false;
       }
       else{
         document.getElementById('recurring').checked=true;
       }
    }
    Good luck,
    Kevin
    A good friend will come and bail you out of jail...
    but a true friend will be sitting next to you saying,
    "Damn... that was fun!"

  3. #3
    on hiatus
    Join Date
    Jun 2013
    Location
    Glasgow
    Posts
    1
    Rep Power
    0
    Hi Builder, Good reply.

    I would rather use jQuery.

    S(document).ready({
    if($('option.a')){
    $('#recurring').checked = false;
    }else{
    $('#recurring').checked = true;
    )};

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •