user1512411
user1512411

Reputation: 63

Displaying elements based on select box choice

I have one select box that hides and displays elements based on its selection.

IN JS PAGE

function showhide() {

    $("div.brandDiv").hide();
    $("select.slct").bind('change', function() {

        $('div.brandDiv').hide();
        var targetId = $(this).val();
        $('div#' + targetId).show();
    });
}

IN HTML call to function showhide()

 <select name="ex" class="slct">

and then divs with id non and yes .

< div id="oui" class="brandDiv">

         <input type="text" name='num' class="numbersonly" maxlength="2" ></input>
                </div>

Its working fine

Problem is when I refresh page it just displays select box with lastly selected option but not elements based on that selection

For example if I have 2 select box options yes and no and if user select yes it shows hello and with no it show By but when i refresh page it shows properly yes or no but not hello or by

I am not very expert .Please help.

Upvotes: 0

Views: 1350

Answers (2)

gaurang171
gaurang171

Reputation: 9090

Here i have done complete bins for above issue, once tryout demo link as shown below:

Demo: http://codebins.com/bin/4ldqp9q

HTML:

<div id="panel">
  <select name="ex" class="slct">
    <option value="div1">
      Option1
    </option>
    <option value="div2">
      Option2
    </option>
    <option value="div3">
      Option3
    </option>
  </select>
  <div id="div1" class="brandDiv">
    Here is content for brand Div 1.
  </div>
  <div id="div2" class="brandDiv">
    Here is content for brand Div 2.
  </div>
  <div id="div3" class="brandDiv">
    Here is content for brand Div 3.
  </div>
</div>

CSS:

.slct{
  border:1px solid #442288;
}
.brandDiv{
  border:1px solid #225599;
  margin-top:5px;
  padding:5px;
  background:#a4c8ed;
  height:30px;
  display:none;
}

jQuery:

function showhide() {
    $('.brandDiv').hide('fast');
    var targetId = $("select.slct").val();
    $('div#' + targetId).show(1000);
}
$(function() {
    showhide();
    $("select.slct").bind('change', showhide);
});

Demo: http://codebins.com/bin/4ldqp9q

Upvotes: 2

Ignas
Ignas

Reputation: 1965

The easiest option would be to trigger the change event. So try something like:

$("select.slct").bind('change', function() {
//your stuff
}).trigger('change');

Upvotes: 1

Related Questions