2

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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/

1 Comment

This seems to make all of the divs appear - I must have made a mistake somewhere in my code I just can' see it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.