Loading HTML files with dropdowns using jQuery

Viewed 48

I am using jQuery .load to load different HTML files into my webpage using a dropdown menu. Each dropdown selection calls the corresponding file. My target div is <div id="targetPane"></div> to load the file. That works fine. I am looking to clean up the code so I dont have to write $('#f1').click(function(){$('#targetPane').load( 'includes/inc_1.html' );}); 50 or so times. The naming convention is that the #f1 will call inc_1.html, #f2 will call inc_2.html and so on. Maybe a solution using a for loop or ('option:selected',this) ? Thanks

$(document).ready(function () {
        $('#f1').click(function(){$('#targetPane').load( 'includes/inc_1.html' );});
        $('#f2').click(function(){$('#targetPane').load( 'includes/inc_2.html' );});
        ..
        ..
        ..
        $('#f50').click(function(){$('#targetPane').load( 'includes/inc_50.html' );});
   
    });

HTML

<form name="courseCalc">
            <select name="myCourses"
             OnChange="location.href=courseCalc.myCourses.options[selectedIndex].value">
                 <option selected>Please Select...</option>
                 <option id="f1" value="#">Item 1</option>
                 ...
                 <option id="f50" value="#">Item 1</option>

            </select>
            </form>
1 Answers

Firstly, note that when working with select elements you are best off using the change event of the parent select element instead of listening for click on the option. It's better practice, more widely supported in various browsers, and follows accessibility guidelines.

With regard to your question, the technique you're looking for is called 'Don't Repeat Yourself', or DRY for short. To achieve it in this case you can hook the change event handler and use get a reference to the select from the Event object passed to the handler. You can amend the HTML to store the URL in the value attribute and then provide it as the argument to load(), like this:

<form name="courseCalc">
  <select name="myCourses" id="courses">
    <option selected>Please Select...
      <option value="includes/inc_1.html">Item 1</option>
      <option value="includes/inc_2.html">Item 2</option>
      <!-- ... -->
      <option value="includes/inc_50.html">Item 50</option>
  </select>
</form>
jQuery($ => {
  $('#courses').on('change', e => {
    $('#targetPane').load(e.target.value);
  });
});

Note that I added an id to the select element to make it easier to retrieve the element in the example, but any selector would work.

Related