问题描述:

I am terrible at Jquery, and can barely understand it as I try to make this code for my site.

My goal is to have Div tags appear when the value that is selected in a form equals that Div tag's name.

Here is what I have:

<form>

<select name="SELECT_Mood_30">

<option value="hap">Happy</option>

<option value="sad">Sadness</option>

<option value="ang">Angry</option>

<option value="gru">Grumpy</option>

</select>

<select name="SELECT_hair_75">

<option value="red">red</option>

<option value="bla">black</option>

<option value="blo">blonde</option>

<option value="bru">brunette</option>

</select>

</form>

Now imagine there's maybe 40, 50, or even 100 different options. Each with a hidden div like below. Upon selecting the option with a value that matches the name of one of these divs, I want the div to appear. When deselecting it I want it to disappear.

<div id="ang" style="display:none;">

SO YOU'RE ANGRY HUH?!

</div>

<div id="sad" style="display:none;">

How can I make you feel better?

</div>

<div id="bla" style="display:none;">

Black hair is really cool

</div>

<div id="red" style="display:none;">

Red hair is nice!

</div>

Is it possible in Jquery to make this? Possibly make it look up the value that is selected, then unhide the named div. The name of the form doesn't matter, it could look up the color red in the mood form and if it appears it could display it anyway. If the named div doesn't exist, then nothing happens and all is good? (no error message or anything)

I've found a few working ones online, but they all seem to require to put each option inside the Jquery, which is what I don't want. I would like it to be flexible enough where you simply have to change the option values and the div names.

Edit: I forgot to mention that say if one select is chosen, such as "sad", and then someone chooses "red", I don't want the div that was named "sad" to disappear. but if the "ang" option is selected, I want the "sad" to disappear. I hope that doesn't confuse things a lot more.

网友答案:

Add a class to all of your div

$("select").change(
function()
{
$(".class").hide();
$(".class[id='"+this.value+"']").show();
})
网友答案:

Give all your divs (hidden) a class say class='foo'

 $(document).ready(function(){
    $('select').change(function(){
    $('.foo').hide();

    $("div[name='"+$(this).val()+"']").show();

    });
    });
网友答案:

You can also use toggle:

jQuery(function() {

   $('select').change(function() {
       // I've use .message to distinguish the divs to show or hide

       var value = $(this).val();
       $('div.message').each(function() { 
              $(this).toggle($(this).attr('id') == value) 
       })

   });

});
相关阅读:
Top