简体   繁体   中英

javascript - hide / show div based on selection

I have a rails form where user has to select a value from a drop down menu and based on that value, the rest fo the form elements are displayed.

<div id="A">
a
b
c
</div>

<div id="B">
x
y
z
c
</div>

<div id="B">
w
a
q
c
</div>

When user selects value A from the select menu, the div with id A is displayed and the rest of the divs are hidden.

The problem is some fields are repeated in the different divs and when user enters a value for field 'a' in div A, this value gets overwritten by the blank value in div B, although div B is hidden from view.

I would like to know whether it's possible to have the same fields in different divs and be able to store the value of the field found in the displayed div only, even if that field is found in other divs.

Many many thanks for any suggestion provided.

Why not give the fields slightly different values, and check which one is actually filled out with an onsubmit function.

You have:

a1 b c1 xyz c2 w a1 q c2

Then in onsubmit: if(a1 !='') { submit a1} else if(a2 != '') {submit a2}

Sorry, not exactly code, but it's a place for you to start from.

When you hide your div, turn on the disabled attribute for all children and when you show a div remove it. Something like this:

var showDiv = function ( id ) {
    var all = [document.getElementById( 'A' ), 
               document.getElementById( 'B' ), 
               document.getElementById( 'C' )],
        cur = document.getElementById( id ),
        inps;

    for (var i = 0, il = all.length; i < il; i++) {

        inps = all[i].getElementsByTagName('input');

        for (var j = 0, jl = inps.length; j < jl; j++) {
            inps[j].setAttribute('disabled', 'disabled');
        }

        all[i].style.display = 'none';

    }

    inps = cur.getElementsByTagName('input');

    for (j = 0, jl = inps.length; j < jl; j++) {
        inps[j].removeAttribute('disabled');
    }

    cur.style.display = 'block';
};

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