SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Addict
    Join Date
    Oct 2003
    Location
    Tenerife, Spain / UK
    Posts
    329
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Disabling fields when a checkbox is ticked

    Hi

    I'm trying to write a script to disable a couple of fields when a checkbox is ticked.

    The following script triggered by an "onchange" call on the checkbox works, but seemingly only if the fields I'm trying to disable follow after the tickbox on the form.
    Code:
    <script language="javascript" type="text/javascript">
    function enabledisable()  
    {
    if (document.form1.field1.disabled==true) {
    	document.form1.field1.disabled=false;
    	document.form1.field2.disabled=false;
    	}
    	else 
    		{document.form1.field1.disabled=true;
    		document.form1.field2.disabled=true;	
    	}
    }
    
    </script>
    How would I modify this script to allow me to disable fields which appear before it on the form?
    David Parkes
    Nuclear Internet - Windows Web Hosting
    http://www.nuclearinternet.com

  2. #2
    SitePoint Addict jtrelfa's Avatar
    Join Date
    Oct 2004
    Location
    Troy, Mi
    Posts
    231
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Let's start with brevity - your code is way too verbose. Second, you should probably check to see if the checkbox is ticked? (forgive the inline javascript; this is just for illustration)

    The important thing you'll notice is that the checkbox passes a reference to itself to the enableDisable function.
    HTML Code:
    <form name="form1">
      <input type="text" name="field1" value="field 1" />
      <input type="checkbox" name="check1" value="whatever" onclick="enableDisable(this);" />
      <input type="text" name="field2" value="field 2" />
    </form>
    Your javascript:
    Code:
    <script type="text/javascript">
    function enableDisable(checkBox) {
      document.form1.field1.disabled = checkBox.checked;
      document.form1.field2.disabled = checkBox.checked;
    }
    </script>
    Hope this helps,

    Jon
    var me = null;


Bookmarks

Posting Permissions

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