JSSuicide
JSSuicide

Reputation: 45

HTML Select dropdown Menu, Jquery Issue

I have had many JS problems all day as I am completely new to JS but I have the following HTML:

<div id = 'drop'>
    <select name = 'option'>
        <option value="form1">Opt1</option>
        <option value="form2">Opt2</option>
        <option value="form3">Opt3</option>
    </select>
</div>

<div id = 'NewContent'>
   //I need different content here depending on selection
    <div id="form1" style="display:none"><div>Content of Formksldmkjlad1</div></div>
   <div id="form2"style="display:none">Content of Form2</div>
   <div id="form3"style="display:none">Content of Form3</div>
</div>

I have an onchange event as seen below in JS:

$('select[name="option"]').change(function() {
    $('#NewContent').children().hide();
   $('#'+$(this).val()).show();
});

I had an issue where all the divs were appearing on page load so I added in the following JS:

$( document ).ready(function() {
  $('#NewContent').children().hide();
});

the issue I have now is that the user has to click in the menu box to another item and then back to the item that they want. For example the dropdown displays:

1.opt1
2.opt2
3.opt3

In order to see the contents of opt the user would firstly have to change the dropdown to opt2 or opt3 and then back to opt1 to see the contents.

^apologies if this doesn't make sense I will work on providing a visual of the issue

Upvotes: 2

Views: 334

Answers (2)

Aaron Cook
Aaron Cook

Reputation: 1324

To seed everything for the first time the page is displayed just add something in your document ready to display the first div.

$( document ).ready(function() { $('#NewContent').children().hide(); $('#form1').show(); });

or use $( document ).ready(function() { $('#NewContent > div:not(:first-child)').hide(); });

in your initial selector to hide everything but the first child div. Then everything should line up for your change events.

Upvotes: 1

dfsq
dfsq

Reputation: 193301

You can trigger change event right after you bind it, in order the correct content div to be displayed if select box comes preselected with some value on page load:

$('select[name="option"]').change(function() {
    $('#NewContent').children().hide();
    $('#'+$(this).val()).show();
})
.trigger('change');

Demo: http://jsfiddle.net/DjgA2/

Upvotes: 0

Related Questions