简体   繁体   中英

Dynamically showing/hiding dynamically-generated <div>s

I am using PHP to dynamically generate a number of <select> fields with two <div> s underneath each. An option is automatically selected and the <div> s are automatically shown/hidden by PHP based on the initial condition, but how can I dynamically switch which <div> is shown/hidden based on a <select> change, in addition to making a form field in that div either disabled or enabled?

For some background, I am displaying all of the information on the page that could be used, but the div s hide each option (using display:none ) that isn't being used, and each unused div also has a disabled form field. When a user selects the other option in the select box, the currently shown div needs to be hidden, the select inside the div needs to be disabled, and the new div needs to be shown and its select needs to be enabled. I'm doing this because each of the hidden/shown form fields has the same name as I'm posting them to a PHP script.

All of the <div> s are in the format of <div id="textdiv-uniqueID"> OR <div id="seldiv-uniqueID"> (where uniqueID is a unique number for each set of div s), and each select is in the format of <select name="uniqueID-good_value"> , where the uniqueID is the same as the corresponding div s.

To recap: I have a dynamically-generated set of select boxes and form fields. Each select box has two associated form fields, each in its own <div> , one of which will be hidden/disabled and the other which will be shown/enabled. When the other option in a given select box is selected, the divs and form fields need to switch roles: the currently hidden/disabled one needs to be shown/enabled, and vice versa.

Here's a jsFiddle with the basics, including my beginning attempt at figuring out the Javascript/jQuery.

In general, something similar to what you need looks like this:

$('#uniqueID-good_value').on('change',function (){
    var val= $(this).val();
    if(val==1) {
        $('textdiv-uniqueID').show();
        $('seldiv-uniqueID').hide();
    }else{
        $('textdiv-uniqueID').hide();
        $('seldiv-uniqueID').show();
    }
});

for your case, you need to work a bit on the logic to make it work smart with the uniqueid.

Can't you just put a class of 'active' or 'hidden' on the relevant fields, and then swap the class when things change?

For instance:

$(".active").removeClass("active").addClass("hidden");

You could put that into an event on your select widgets (I'm not sure what all the available events are, but there must be something like onselect or onselected, and there's always onmouseup)

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