0
\$\begingroup\$

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();
 }
}
asked Apr 12, 2012 at 20:22
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

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.

answered Apr 12, 2012 at 20:44
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.