SitePoint Sponsor

User Tag List

Results 1 to 16 of 16
  1. #1
    SitePoint Enthusiast Joel Farris's Avatar
    Join Date
    Jul 2004
    Location
    Nashville, TN
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Lightbulb Can radio buttons toggle visibility in an either/or scenario?

    Hi all,

    I've got a fully functioning form on a production website that I need to add some more features to. Why does this always happen after a page goes live? Have a look at the webpage I'm working on.

    The "Subcriptions" form on the left needs two drop-downs. Each of the drop-down menus will hold job descriptions for Company or Personnel respectively.

    The user only needs access to one of these drop-downs, not both. I need to put a pair of radio group buttons that will allow me to toggle between these two drop down menus in an either/or scenario.

    Here's what the new section should look like:
    PHP Code:
    Is this a company?  YES NO
    if (company) == "YES"
        
    Enter Company Name
        Choose company job description

    if (company) == "NO"
        
    Choose personnel job description 
    I've been looking over the Trimming Form Fields tutorial, the Quirksmode - Usable Forms site, and I can't wrap my brain around how to modify their ultra-cool tutorials for my situation. Any help on this would be greatly appreciated.
    Last edited by Joel Farris; Aug 17, 2006 at 16:13.
    <!-- Joel Farris -->
    "I woulda brought my printer to this meeting,
    but they wouldn't allow any Sharp objects on the plane!"

  2. #2
    .* draziW tnioPetiS *. bronze trophy
    Join Date
    Jun 2004
    Location
    "Then I figure the most good good guy will win."
    Posts
    1,666
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hmm, maybe this will help.... here is some javascript that shows/hides form elements based on drop-down selections:

    HTML Code:
    <script language=javascript>
    function show_hide_location() {
       var country_val=document.registration.country.options[document.registration.country.selectedIndex].value;
       if(country_val == 'US') {
         var x = document.getElementById('location_class');
         x.style.display = 'block';
       } else {
         var x = document.getElementById('location_class');
         x.style.display = 'none';     
       }
    }
    </script>
    The above is just going to show a dropdown of US states if the person is from the US... next function:

    HTML Code:
    <script language=javascript>
    function show_hide_address() {
       var state_val=document.registration.state.options[document.registration.state.selectedIndex].value;
       if(state_val == 'OR') {
         var x = document.getElementById('address_class');
         x.style.display = 'block';
       } else {
         var x = document.getElementById('address_class');
         x.style.display = 'none';     
       }
    }
    </script>
    Now, if the user chooses Oregon the form will show additional fields (address, phone, name...)

    Here is the relevant html:

    HTML Code:
    <label for="fm-country">Where do you live?</label>
    <select id="fm-country" name="country" onchange="show_hide_location()"> 
    	<option value="">Choose Country...</option>
    	<option value="US">United States</option> 
    	<option value="CA">Canada</option> 
    	<option value="MX">Mexico</option> 							<option value="GU">Guam</option> 								<option value="PR">Puerto Rico</option> 
    	<option value="OT">Other U.S. territories</option> 
    	<option value="OT">Other</option> 
    </select>
    HTML Code:
    <div class="location_class" id="location_class" style="display:none">
    	<label for="fm-state">Choose State:</label>
    	<select id="fm-state" name="state" onchange="show_hide_address()"> 
    		<option value="">State...</option>
    		<option value="AL">Alabama</option>
    		<option value="AK">Alaska</option>
    		<option value="AR">Arkansas</option>
    		...
    		...
    		<option value="OR">Oregon</option>
    		...
    		...
    		<option value="WY">Wyoming</option>
    	</select>
    </div>
    HTML Code:
    <div class="address_class" id="address_class" style="display:none">
    	<label for="fm-address1">Address:</label>
    	<input id="fm-address1" name="address1" type="text" />
    	<label for="fm-address2">Apt. #:</label>
    	<input id="fm-address2" name="address2" type="text" />
    	<label for="fm-city">City:</label>
    	<input id="fm-city" name="city" type="text" />
    </div>
    Not sure if that will help, and I am sure others have much better ways of doing the same thing... anyway, hopefully it gives you some inspiration!

    Cheers,
    Micky

  3. #3
    SitePoint Enthusiast Joel Farris's Avatar
    Join Date
    Jul 2004
    Location
    Nashville, TN
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I like what you've done with this idea, and I think it's going to help me, so thanks for posting it. I'm off to QuirksMode.org for some in-depth JavaScript samples that, hopefully, will allow me to modify what you've posted so that it works with a radio button set instead of a dropdown menu set.

    Thanks again! I'll report back here when I've figured it out. I always do.
    <!-- Joel Farris -->
    "I woulda brought my printer to this meeting,
    but they wouldn't allow any Sharp objects on the plane!"

  4. #4
    SitePoint Enthusiast Joel Farris's Avatar
    Join Date
    Jul 2004
    Location
    Nashville, TN
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    First draft of javascript either/or toggle for divs inside a form

    Here's the first draft of the javascript I wrote based upon Micky's answer. Keeping in mind that I've never written any javascript before, would someone like to tell me why this function correctly hides both divs when the page is first loaded, but then shows the personnelInfo div whenever either button is pushed, yet it won't switch the visibility?

    Javascript code:
    Code:
    // Toggle the visibility of two div elements within a fieldset.
    // This is an either/or selection based on a Yes/No radio group.
    function toggleDivDisplay() {
    	// Iterate throught the companyToggleButton radio group to find which one is pushed.
    	for (i=0;i<document.subscriptionForm.companyToggleButton.length;i++) {
    		if (document.subscriptionForm.companyToggleButton[i].checked) {
    			user_input = document.subscriptionForm.companyToggleButton[i].value;
    		}
    	}
    	if (user_input == 'true') {
    		// Only show the companyInfo
    		var companyDivToggle = document.getElementById('companyInfo');
    		companyDivToggle.style.display = 'block';
    		var personnelDivToggle = document.getElementById('personnelInfo');
    		personnelDivToggle.style.display = 'none';
    	} else if (user_input == 'false') {
    		// Only show the personnelInfo
    		var companyDivToggle = document.getElementById('companyInfo');
    		companyDivToggle.style.display = 'none';
    		var personnelDivToggle = document.getElementById('personnelInfo');
    		personnelDivToggle.style.display = 'block';
    	} else {
    		// If both of the above checks fail, we show both fields
    		var companyDivToggle = document.getElementById('companyInfo');
    		companyDivToggle.style.display = 'block';
    		var personnelDivToggle = document.getElementById('personnelInfo');
    		personnelDivToggle.style.display = 'block';
    	}
    } // Closes the toggleDivDisplay function
    Html code:
    HTML Code:
    <fieldset><legend>Industry Info</legend>
    Is the subscription for a company?
    <label for="companyToggleButton">Yes</label>
    <input id="companyToggleButton" name="companyToggleButton" type="radio" class="radioButton" onChange="toggleDivDisplay()">
    <label for="companyToggleButton">No</label>
    <input id="companyToggleButton" name="companyToggleButton" type="radio" class="radioButton" onChange="toggleDivDisplay()">
    <br />
    
    <div id="companyInfo" class="companyInfo" style="display:none">
    	<label for="companyName" accesskey="">Company Name</label>
    	<input id="companyName" name="companyName" type="text" tabindex="" maxlength="50" />
    	<br />
    
    	<label for="companyJob" accesskey="">*Company Job</label>
    	<select id="companyJob" name="companyJob" tabindex="19" accesskey="">
    		<option value="None" selected="selected">-- select a job description --</option>
    		<option value="President">President</option>
    		<option value="Vice President">Vice President</option>
    		<option value="Manager">Manager</option>
    	</select>
    	<br />
    </div>
    
    <div id="personnelInfo" class="personnelInfo" style="display:none">
    	<label for="personnelJob" accesskey="">*Personnel Job</label>
    	<select id="personnelJob" name="personnelJob" tabindex="17" accesskey="">
    		<option value="None" selected="selected">-- select a job description --</option>
    		<option value="A/V Tech">A/V Tech</option>
    		<option value="Backline Tech">Backline Tech</option>
    		<option value="Bus Driver">Bus Driver</option>
    	</select>
    	<br />
    </div>
    </fieldset>
    <!-- Joel Farris -->
    "I woulda brought my printer to this meeting,
    but they wouldn't allow any Sharp objects on the plane!"

  5. #5
    .* draziW tnioPetiS *. bronze trophy
    Join Date
    Jun 2004
    Location
    "Then I figure the most good good guy will win."
    Posts
    1,666
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi,

    HTML Code:
    <div id="companyInfo" class="companyInfo" style="display:none">
    See the style "display:none", that is why they are hidden to start with (I would do via external style sheet).

    As for your other question...

    Looking over code now... post back in a min.

  6. #6
    .* draziW tnioPetiS *. bronze trophy
    Join Date
    Jun 2004
    Location
    "Then I figure the most good good guy will win."
    Posts
    1,666
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ah, here is the prob:

    HTML Code:
    <label for="companyToggleButton">Yes</label>
    <input id="companyToggleButton" name="companyToggleButton" type="radio" class="radioButton" onChange="toggleDivDisplay()" value="true">
    <label for="companyToggleButton">No</label>
    <input id="companyToggleButton" name="companyToggleButton" type="radio" class="radioButton" onChange="toggleDivDisplay()" value="false">
    You did not have a value for the radio buttons.

    Needed "value="true"" or "value="false"".

    Got it working here:

    http://www.ambiguism.com/sandbox/toggle.html

  7. #7
    SitePoint Enthusiast Joel Farris's Avatar
    Join Date
    Jul 2004
    Location
    Nashville, TN
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Lightbulb

    Quote Originally Posted by mhulse
    Ah, here is the prob: You did not have a value for the radio buttons.
    Needed "value="true"" or "value="false"".
    Well! That's the last time I let Dreamweaver create a radio button group for me! Heh. I would normally have hand-coded them like I do everything else, but I could not remember how to make a radio group. Instead, I ended up with a pair of radio buttons that could both be pressed down at the same time. To my way of thinking, that's not a radio button set, but such is a story for another time...

    So I dropped into Dreamweaver and made a radio group. I didn't see that there were no values assigned to these two buttons, but it makes perfect sense that my lovingly massaged script, crafted from your initial reply, wasn't working. It didn't have anything to go on!

    Thanks for setting me straight.
    <!-- Joel Farris -->
    "I woulda brought my printer to this meeting,
    but they wouldn't allow any Sharp objects on the plane!"

  8. #8
    .* draziW tnioPetiS *. bronze trophy
    Join Date
    Jun 2004
    Location
    "Then I figure the most good good guy will win."
    Posts
    1,666
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    No problem.

    Glad you got it working.

    Nice work btw, and I am sure it will help others in the future.

    Cheers,
    Micky

  9. #9
    SitePoint Enthusiast Joel Farris's Avatar
    Join Date
    Jul 2004
    Location
    Nashville, TN
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Bummer! This doesn't work at all in Safari 2.0.4 (latest version). It appears my toggleDivDisplay javascript function won't fire when used by the onChange() event.

    Wow. I was so ecxited too.
    <!-- Joel Farris -->
    "I woulda brought my printer to this meeting,
    but they wouldn't allow any Sharp objects on the plane!"

  10. #10
    SitePoint Enthusiast Joel Farris's Avatar
    Join Date
    Jul 2004
    Location
    Nashville, TN
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here's my most current version of the script, in case anybody wants it. I've re-edited some stuff to try and make it more reusable in the future. Also, it should be noted that Safari doesn't like the onChange event handler, and therefore completely ignores this whole script. Bummer

    Code:
    // Toggle the visibility of two div elements within a fieldset.
    // This is an either/or selection based on a Yes/No radio group.
    function toggleDivDisplay() {
    	// Iterate throught the companyToggleButton radio group to find which one is pushed.
    	for (i=0;i<document.subscriptionForm.companyToggleButton.length;i++) {
    		if (document.subscriptionForm.companyToggleButton[i].checked) {
    			var user_input = document.subscriptionForm.companyToggleButton[i].value;
    		}
    	}
    	if (user_input == 'true') {
    		// Only show the companyInfo
    		var companyDivToggle = document.getElementById('companyInfo');
    		companyDivToggle.style.display = 'block';
    		var personnelDivToggle = document.getElementById('personnelInfo');
    		personnelDivToggle.style.display = 'none';
    	} else if (user_input == 'false') {
    		// Only show the personnelInfo
    		var companyDivToggle = document.getElementById('companyInfo');
    		companyDivToggle.style.display = 'none';
    		var personnelDivToggle = document.getElementById('personnelInfo');
    		personnelDivToggle.style.display = 'block';
    	} else {
    		// If both of the above checks fail, we show both fields
    		var companyDivToggle = document.getElementById('companyInfo');
    		companyDivToggle.style.display = 'block';
    		var personnelDivToggle = document.getElementById('personnelInfo');
    		personnelDivToggle.style.display = 'block';
    	}
    } // Closes the toggleDivDisplay function
    The personnel div now starts off as display:block and the company div as display:none. This concept will at least show the user that there is SOMETHING to fill out in this section, and hopefully will give them the idea that they can toggle back and forth.

    Now for my next question. Is there a way that javascript can perform an onLoad(), at least I think it's onLoad(), when the page first loads so that I can hide one of those divs? I don't really want to set display:none in the page's html because if the user has javascript disabled, they'll never be able to accesss that portion of the form.
    Last edited by Joel Farris; Aug 18, 2006 at 08:19.
    <!-- Joel Farris -->
    "I woulda brought my printer to this meeting,
    but they wouldn't allow any Sharp objects on the plane!"

  11. #11
    .* draziW tnioPetiS *. bronze trophy
    Join Date
    Jun 2004
    Location
    "Then I figure the most good good guy will win."
    Posts
    1,666
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sounds like you should use "onclick" instead.

    You might also want to use vars for some of your code... like so:

    Code:
    var what_chosen = document.subscriptionForm.companyToggleButton;
    Now you can use the var what_chosen and shorten code and boost readability.

    Looks good though.
    Cheers,
    Micky

  12. #12
    SitePoint Enthusiast Joel Farris's Avatar
    Join Date
    Jul 2004
    Location
    Nashville, TN
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by mhulse
    Sounds like you should use "onclick" instead.
    I was afraid of replacing onChange() with onClick() because of accesssibility reasons. Wouldn't that require the use of mouse navigation exclusive of keyboard navigation?

    You might also want to use vars for some of your code... like so:

    Code:
    var what_chosen = document.subscriptionForm.companyToggleButton;
    Now you can use the var what_chosen and shorten code and boost readability.
    I do that all the time in PHP, but now that I know it can be done in javascrit as well, I'll be a lot better off. Thanks for that tidbit, and for the complements on My First Script.
    <!-- Joel Farris -->
    "I woulda brought my printer to this meeting,
    but they wouldn't allow any Sharp objects on the plane!"

  13. #13
    .* draziW tnioPetiS *. bronze trophy
    Join Date
    Jun 2004
    Location
    "Then I figure the most good good guy will win."
    Posts
    1,666
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Joel Farris
    I was afraid of replacing onChange() with onClick() because of accesssibility reasons. Wouldn't that require the use of mouse navigation exclusive of keyboard navigation?
    Ah, that is definitely a concern (accessibility)... Here are a few interesting reads on that:

    The trouble with onclick
    All onclick event handlers have an associated onkeypress event handler.
    Using the TabIndex Attribute

    Looks like the best bet is to use onclick() and onkeypress() and use a simple function to test for key pressed... the third link above has an example... not sure how contemporary of a solution that is, but maybe worth trying.

    Cheers,
    Micky
    Last edited by mhulse; Aug 18, 2006 at 13:18. Reason: 450

  14. #14
    SitePoint Enthusiast Joel Farris's Avatar
    Join Date
    Jul 2004
    Location
    Nashville, TN
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by mhulse
    Ah, that is definitely a concern (accessibility)...
    {snip}
    Looks like the best bet is to use onclick() and onkeypress() and use a simple function to test for key pressed... the third link above has an example... not sure how contemporary of a solution that is, but maybe worth trying.
    I will change to onClick, yet without the onKeyPress. From my reading and study about this subject (08/24/2006) it seems that the onKeyPress can actually detract from the functionality of accesskeys, and it certainly seems to get in the way of the "Tab to a form element and activate it by pressing Enter" functionality.

    I'm led to understand that most web browsers these days generate a "mouse click" when the element is Tabbed to and the Enter key is pressed. That satisfies my basic keyboard navigation needs. I'm not building a website specifically for mousless users, but if I can't operate my own creation with the keyboard, and my hand has to stray to the mouse in order to accomplish a task, I have failed my worldwide audience.

    And now, back to the grind for me!
    <!-- Joel Farris -->
    "I woulda brought my printer to this meeting,
    but they wouldn't allow any Sharp objects on the plane!"

  15. #15
    SitePoint Enthusiast Joel Farris's Avatar
    Join Date
    Jul 2004
    Location
    Nashville, TN
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok, so now I'm trying to generate an onLoad() that will write some inline CSS into div tags. The goal is to hide both of the divs that hold the respective drop down menus for Company or Individual, and only show them when the appropriate radio button is toggled.

    I feel that if I can use javascript to make a <div> tag into a <div style="display:none"> as the page loads, I will have successfully hidden the fields from a javascript-capable browser while a javascript-disabled browser would show BOTH of the fields.

    It's ok to see both fields if you don't have javascript enabled. The php backend will only process the data that correlates to the radio group that's checked. I've included some extra text for the javascript-neutered users too.

    Here's what I have so far.
    Code:
    window.onload = function() {
       doThis();
     }
    What do I place in the doThis() function that will write a line of CSS text into my page at the exact spot within an html tag? I can't seem to find this answer anywhere on the net, but it may be that I don't know what term to search for.
    <!-- Joel Farris -->
    "I woulda brought my printer to this meeting,
    but they wouldn't allow any Sharp objects on the plane!"

  16. #16
    .* draziW tnioPetiS *. bronze trophy
    Join Date
    Jun 2004
    Location
    "Then I figure the most good good guy will win."
    Posts
    1,666
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi,

    Try these functions... put in external JS file:

    (external.js)
    Code:
    <!--//--><![CDATA[//><!--
    /* event_attach() takes care of attaching event handlers (functions) to events. 
     * this simplifies the process of attaching multiple handlers to a single event
     *
     * NOTE: the onload stack is executed in a LIFO manner to mimic 
     *       IE's window.attachEvent function. However, Opera also has its own
     *       window.attachEvent function which executes the onload stack in a 
     *       FIFO manner. FIFO is better, but IE has a larger user base, so
     *       LIFO is the way we go.
     */
    function event_attach(event, func) {
    	if (window.attachEvent) {
    		window.attachEvent(event, func);
    	}
    	else {
    		if((typeof(func)).toLowerCase() != 'function') {
    			return;
    		}
    		if((typeof(document.event_handlers)).toLowerCase() == 'undefined') {
    			document.event_handlers = new Array();
    		}
    		if((typeof(document.event_handlers[ event ])).toLowerCase() == 'undefined') {
    			document.event_handlers[ event ] = new Array();
    		}
    		if((typeof(eval('window.' + event))).toLowerCase() != 'function') {
    			eval('window.' + event + ' = function () { if ((typeof(document.event_handlers[ \'' + event + '\' ])).toLowerCase() != \'undefined\') { for (i = document.event_handlers[ \'' + event + '\' ].length - 1 ; i >= 0  ; i--) { document.event_handlers[ \'' + event + '\' ][ i ](); } } } ');
    		}
    		document.event_handlers[ event ][ document.event_handlers[ event ].length ] = func;
    	}
    }
    function hide() {
    	var node1 = document.getElementById("test");
    	/* Add more nodes here. */
    	if(node1) { node1.style.display = 'none'; }
    }
    //--><!]]>
    In head:

    HTML Code:
    <!-- .JS: -->
    <script type="text/javascript" src="/js/external.js"></script>
    <script type="text/javascript">
    	<!--
    		/* Put your javascript here: */
    		event_attach('onload', hide);
    		/**/
    	//-->
    </script>
    in body somewhere...

    HTML Code:
    <di id="test">hi</div>
    Here is example.

    P.S. Why are girlfriends crazy?
    Last edited by mhulse; Aug 24, 2006 at 01:35.


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
  •