简体   繁体   中英

jQuery or Javascript solution for radio buttons and showing/ hiding divs

I have, what on initial viewing, is a simple requirement to show/hide two divs based on a users response to radio buttons.

See the JsFiddle: http://jsfiddle.net/P75cv/

The real complexity is as follows.

Div one is to be shown if any of the questions has a radio button value of 2 or 1. Div two is only to be shown if any of the questions don't have a value of 2, 1 or -1.

However, I also need a further check to do the following, if div one has been shown and a user goes back and changes their response so that no radio buttons have a value or 2 or 1, then div one needs to be hidden and div two shown. Similarly, if div two is being shown but the user goes back and changes their responses so that any of the radio buttons have a value of 2 or 1, div two needs to be hidden and div one shown.

And finally, the user has the option of saving and coming back to the page - if they do, I need the right div to be shown based (on page load?).

The simple part of showing and hiding divs I can do, in both jQuery and Javascript but this level of complexity is really causing me a headache - can anyone offer an insights or solutions?

I would create your basic functions that perform the show/hide routine. Then populate an array that has all the values of the radio buttons, check if the array contains the values you are looking for, and then call the proper function.

I would use JQuery cookie to store what div should be shown when the user saves and comes back to the page.

So, answering my own question - I have used the following code:

<?php
function checking() {
count = 0;
";
for ($i=1; $i<=10; $i++){
echo"   q".$i." = $('input[name=\"q".$i."\"]:checked').val();
    if(q".$i." == 1 || q".$i." == 2){
            document.getElementById('disagree').style.display = 'block';
            document.getElementById('agree').style.display = 'none';
        count = 1;
    }
    ";

    }

    echo" 

    if (count==0){
        document.getElementById('disagree').style.display = 'none';
        document.getElementById('agree').style.display = 'block';
    }

}
?>

As you can see, I have 10 questions on the page and use PHP to write the script out and it works. I have no doubt whatsoever that there are far more efficient and elegant ways of achieving the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM