开发者

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 d开发者_JAVA百科iv 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.


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';
};


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 x y z 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜