MillRunner MillRunner - 7 months ago 9
Javascript Question

Why is my div not showing up with jquery show

I have code in html like this:

<div id="answerTypeSection" style="visibility: hidden">
<div class="row">
<div class="col-md-2">adfadfafasdfasdfas</div>
</div>
<label class="control-label">adfa</label>
adfaf
</div>

<select id="answerType" class="form-control">
<option></option>
<option>Text</option>
<option>A or B (Boolean)</option>
<option>Numeric</option>
<option>Photo</option>
<option>Files</option>
<option>Multi (combo)</option>
</select>


Then in javascript

$("#answerType").change(function () {
var answerType = $('#answerType').val();
console.log('in');
var showType;

switch(answerType) {
case "Numeric":
showType = "N";
console.log('numeric');
$("#answerTypeSection").show();
break;
default:
showType = "what";
// hide?
console.log('hide');
$("#answerTypeSection").hide();
break;

}
// required
});


console.log does end up showing 'in' and 'numeric' , so it must be something else that i'm not doing right.
answerTypeSection
should show shouldn't it?

Answer

Try to get the text of selected option element,

$("#answerType").change(function() {
  var answerType = $('#answerType option:selected').text(), showType;
  switch (answerType) {
    case "Numeric":
      showType = "N";
      $("#answerTypeSection").show();
      break;
    default:
      showType = "what";
      $("#answerTypeSection").hide();
      break;
  }
});

DEMO

Also, .show() and .hide() would not work with visible:hidden. You have to use display:none for making use of it. If you want to use visible property for sure then you have to change the property by using .css().


And the best approach for this kind of situation would be setting the value attribute for the options of your select element,

<select id="answerType" class="form-control">
  <option value="">---</option>
  <option value="Text">Text</option>
  <option value="A or B (Boolean)">A or B (Boolean)</option>
  <option value="Numeric">Numeric</option>
  <option value="Photo">Photo</option>
  <option value="Files">Files</option>
  <option value="Multi (combo)">Multi (combo)</option>
</select>

And for handling the above html you have to rewrite your Js as below,

$("#answerType").change(function() {
  var answerType = $(this).val();
  var showType;
  switch (answerType) {
    case "Numeric":
      showType = "N";
      $("#answerTypeSection").show();
      break;
    default:
      showType = "what";
      $("#answerTypeSection").hide();
      break;
  }
});

DEMO