Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I need help refactoring the javascript. http://jsfiddle.net/BDLYP/

I was able to hide and show fields, but I know this can be improved upon.

If #state is empty, hide #high-schools and #other_high_schools

If #state is picked, show #high-schools and show #other_high_schools (if #high-schools is empty)

I imagine the multiple .live can be cut down. I am fairly new to javascript/jQuery

<select name="state" id="state">
    <option value=""></option>
    <option value="NY">NY</option>
    <option value="CA">CA</option>
</select>

<div id="high-schools">
    <select name="high_school_id" id="high_school">
        <option value=""></option>
        <option value="1">Degrassi High</option>
        <option value="2">Bayside High</option>
    </select>
</div>

<div id="other_high_school">
    <p>Enter hs if your school is not listed above 
        <input type="text" name="other_high_school" id="other-hs-field" /></p>
</div>
​
$(document).ready(function() {
   checkHighSchool();

   $('#high_school').live('change', function() {
    checkHighSchool();
  });   

  $('#state').live('change', function() {
    checkHighSchool();
  });          
});

function checkHighSchool() {
  var state = $("#state").val();
  var high_school = $("#high_school").val();

  if(state) {
    $("#high-schools").show();
  }

  if(!state) {
    $("#other_high_school").hide();
    $("#high-schools").hide();
    $("#other-hs-field").val('');
    //alert('no state selected');
  }

  if(high_school && state) {
    $("#other_high_school").hide();
    $("#other-hs-field").val('');
  }

  if(!high_school && state) {
    $("#other_high_school").show();
  }
}
share|improve this question

1 Answer 1

I will give you a sample which is very simplified. I hope you can understand what I am doing here.

HTML

<select class="toggle-data">
    <option></option>
    <option value="1" data-toggle="#foo-one">foo one</option>
    <option value="2" data-toggle="#foo-two">foo two</option>
</select>

<div id="foo-one" style="display: none;">
    foo one
</div>

<div id="foo-two" style="display: none;">
    foo two
</div>

​ JS/jQuery

$('.toggle-data').on('change', function() {
    var toggle = this.options[this.selectedIndex].getAttribute('data-toggle'),
        toggle_class = 'unique_classname';
    $('.'+toggle_class+', '+toggle).toggle().removeClass(toggle_class);
    $(toggle).addClass(toggle_class);
});
​

Now you have a single function to do all of your show/hiding and you would just format you html accordingly.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.