Solved

Looping Over Variable Radio Button Pairs

Posted on 2011-03-01
4
280 Views
Last Modified: 2012-05-11
Hi,
I am a newbie in JS so please be patient.  I also think this may be a tough question?

I have a page with a variable set of radio button pairs (ship email = 1, ship usps = 2).  The number of pairs is in a hidden text field (name=numRadio).  Each set of radio buttons has a unque ID=Radio_1, Radio_2 etc.

Objective:
When a radio button is changed by a user, I need to create a script that will look at all the radio button pairs:

Condition:  If they are all selected and have the same value = 1
  change the value and class of a set of address input text fields.

Condition:  If they are all selected and have the same value = 2
  change the value and class off a different set of  address input text fields.

Otherwise, Do nothing.

The basic objective is that if all the products are chosen to be sent by email, then disable the physical addess side of the page.  If the are all selected to be sent by mail, then disable the email side of the page.  If the are mixed then display both sides of the page.

I think I know how to manipulate the input fields (more or less) but I don't know how to test for the conditions above.

I think this may be complicated but many very smart folks are in this forum!!!

Thanks in advance for your expertise,
hefterr

 
0
Comment
Question by:hefterr
  • 2
  • 2
4 Comments
 
LVL 10

Accepted Solution

by:
P1ST0LPETE earned 500 total points
Comment Utility
I think this is what you are after except it's a little hard to tell without seeing some of your markup.
Also, this is using some jQuery (http://jquery.com) which is a free JavaScript library that allows you to write JavaScript more easily.
Anyway, below is a complete working example, just copy all the code into an html file, load it up, and try it out.

Also note that the way you name your radio buttons is key to how this script works.  You can see in the markup below how I am naming the radio button pairs: [radio1_ShipEmail, radio1_ShipUps] , [radio2_RunFast, radio2_RunSlow] etc.  The end part of the name"_ShipUps" or "_RunFast" etc, doesn't matter.  What does matter is the prefix on the name: "radio1", "radio2", etc, which seems to be what you were talking about in your original post.  Anyway the following lines of script are looking for prefixes like that:

    var pairIndex = this.id.substring(5, 6);
    $('[id*="radio' + pairIndex + '"]').attr('checked', false);

    var firstValue = $('[id*="radio1"]:checked').val();

    if ($('[id*="radio' + i + '"]:checked').val() != firstValue)

So if want to change the naming, you'll need to edit these lines.
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Radio Select</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function ()
        {
            //Allows only one radio option to be selected in each pair:
            $('input:radio').click(function ()
            {
                var pairIndex = this.id.substring(5, 6);
                $('[id*="radio' + pairIndex + '"]').attr('checked', false);
                this.checked = true;
                CheckRadioValues();
            });

            function CheckRadioValues()
            {
                var numRadio = $('#numRadio').val();
                var firstValue = $('[id*="radio1"]:checked').val();
                var allRadioValuesSame = true;

                for (var i = 1; i <= numRadio; i++)
                {
                    if ($('[id*="radio' + i + '"]:checked').val() != firstValue)
                    {
                        allRadioValuesSame = false;
                        break;
                    }
                }

                if (allRadioValuesSame)
                {
                    if (firstValue == 1)
                    {
                        alert('All have values of 1');
                        //Do something when all have value of 1
                    }
                    else
                    {
                        alert('All have values of 2');
                        //Do something when all have value of 2
                    }
                }
                else
                {
                    alert('Values are mixed or some are not checked.');
                    //Do nothing as they have mixed values
                }
            }
        });
    </script>
</head>
<body>
    <input id="numRadio" type="hidden" value="3" />
    <div>
        <input id="radio1_ShipEmail" type="radio" value="1" />
        <label for="radio1_ShipEmail">Ship Email</label>
        <input id="radio1_ShipUps" type="radio" value="2" />
        <label for="radio1_ShipUps">Ship UPS</label>
        <br />
        <input id="radio2_RunFast" type="radio" value="1" />
        <label for="radio2_RunFast">Run Fast</label>
        <input id="radio2_RunSlow" type="radio" value="2" />
        <label for="radio2_RunSlow">Run Slow</label>
        <br />
        <input id="radio3_DrinkWater" type="radio" value="1" />
        <label for="radio3_DrinkWater">Drink Water</label>
        <input id="radio3_DrinkSoda" type="radio" value="2" />
        <label for="radio3_DrinkSoda">Drink Soda</label>
    </div>
</body>
</html>

Open in new window

0
 
LVL 1

Author Comment

by:hefterr
Comment Utility
Hi P1ST0LPETE,
Thanks for this sophisticated script!!  It's just what I needed.

I am not familar with JQuery (I know what is - but have never used it).  When you have your Alert function, can I substitue standard JavaScript such as:
   document.getElementById('nameID').value     = '';

I'm not sure have to manipulate the input field values as I don't see where the JQuery is invoked by the radio buttons onclick?

Thanks again for you time!!!

hefterr
0
 
LVL 10

Expert Comment

by:P1ST0LPETE
Comment Utility
Ok, sorry for the late reply, just started a new job and don't have the time currently to answer questions at work as I'm learning a whole new system :-).

Anyway, yes, I have the alerts placed where I do so that you can have a visual representation of the code executing correctly.  Simply delete the alerts and replace them with whatever code you want.

Concerning jQuery, I know you said you are new to JavaScript, but jQuery really isn't all that hard, and as I said in my post above, it actually makes writing JavaScript a lot more easy.  One of the cool things about jQuery is it allows you to separate your JavaScript from your html markup, similar to how using CSS allows you to separate your styling from your markup.  The result is clean pure html markup with no JavaScript or styling mixed in.

To do this you add your event handlers to elements using jQuery, and you do this inside of the $(document).ready() event.

Little basics first on $(document).ready():
The "$" is shorthand for "jquery" (i.e. it could be written "jquery(document).ready()") and "document" is the object we are passing into jQuery. Then we are calling the "ready" function.  The ready function fires when the object, in this case your html document, is fully loaded and ready to be manipulated.  Finally we pass an anonymous function (i.e. a function without a name) into the ready event as a parameter, which gets ran when the ready event fires. Which gives us this:

$(document).ready(function()
{
       //This code begins to run ONLY when the html document is fully loaded into the browser
});

Inside of the ready event in my original post, you see the following block of code:

//Allows only one radio option to be selected in each pair:
$('input:radio').click(function ()
{
         var pairIndex = this.id.substring(5, 6);
         $('[id*="radio' + pairIndex + '"]').attr('checked', false);
         this.checked = true;
         CheckRadioValues();
});

This is how you add event handlers to elements using jQuery, and is great example of the power of jQuery and showcases where jQuery gets it's name, as we a literally using JavaScript (i.e. the JavaScript written in the jQuery library) to query the DOM.

This line of code:
$('input:radio').click(function()

Is basically saying: "For every single input element on the page, IF it is of type 'radio', do the following code when it is clicked".

$('input:radio').click(function ()
{
         //Anytime ANY radio button on the page is clicked, code here will run
});

Again, notice the anonymous function being passed into the click() event.  The anonymous function is the code block that is ran when the click event fires.  Once inside the anonymous function, to access the element that triggered the event, you use the key work 'this'. So:

$('input:radio').click(function ()
{
         alert(this.id);  //<-- will popup the ID of the radio button that was clicked.
});

There are multiple ways to use jQuery to query the DOM.

You can access elements by their class name:
$('.classname')  //<-- this grabs ALL elements that have the class "classname" applied to them

Or you can access an element directly by ID, like this:
$('#nameID')

So for example your question about document.getElementById('nameID').value = ""
This is the jQuery equivalent:     $('#nameID')val("");

Or if you wanted to manipulate the element that triggered the event you use this:
$(this).val("");
Or you could do this: this.value = "" //which is standard JavaScript

You can can also query elements based on their attribute values:
$('[type="textbox"]').  //<-- grabs all elements on the page that has a 'type' attribute with the value of "textbox"
Which could also be written:    $('input:textbox')
$('[type="textbox"]) == $('input:textbox')

Continuing with the querying of element attribute values, you can use the * sign which means "begins with"
So   $([name*="tbQuestion"]')   would grab the following elements because their 'name' attributes all begin with "tbQuestion"

<input type="textbox" name="tbQuestion1" />
<input type="textbox" name="tbQuestion2" />
<input type="textbox" name="tbQuestion3" />

Which is what I'm doing here, except using the ID attribute:
$('[id*="radio' + pairIndex + '"]').attr('checked', false);

-----------------------------------------------------------------------------------

Hopefully that helps explain it a bit more, let me know if you still have questions.

hmmm....... looking over my response, maybe I should have just linked you to a jQuery tutorial :-)
0
 
LVL 1

Author Comment

by:hefterr
Comment Utility
P1ST0LPETE,
Thanks so much for your help and introduction to JQuery.  Jquery Is very powerful but I have heard it has a bit of a steap learning curve.  I will definately look into it.

Thanks again for your expertise.

hefterr
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now