Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think I understand what you're asking here, but I could be wrong. Assuming I do, I would add classes or IDs to represent a linkage between the elements. For instance:</p> <pre><code>&lt;input type="hidden" name="degree" id="degree" /&gt; &lt;div id="degree_selectable_control" class="selectable_control"&gt; &lt;a href="#" class="prev"&gt;Prev&lt;/a&gt; | &lt;a href="#" class="next"&gt;Next&lt;/a&gt; &lt;/div&gt; &lt;ul id="degreee_selectable" class="selectable"&gt; &lt;li&gt;Associates&lt;/li&gt; &lt;li&gt;Bachelor's&lt;/li&gt; &lt;li&gt;Graduate&lt;/li&gt; &lt;li&gt;Other&lt;/li&gt; &lt;/ul&gt; &lt;input type="hidden" name="salary" id="salary" /&gt; &lt;div id="salary_selectable_control" class="selectable_control"&gt; &lt;a href="#" class="prev"&gt;Prev&lt;/a&gt; | &lt;a href="#" class="next"&gt;Next&lt;/a&gt; &lt;/div&gt; &lt;ul id="salary_selectable" class="selectable"&gt; &lt;li&gt;&gt; $20,000&lt;/li&gt; &lt;li&gt;$20,000 - $35,000&lt;/li&gt; &lt;li&gt;$35,000 - $50,000&lt;/li&gt; &lt;li&gt;&lt; $50,000&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Then you could refactor your existing JavaScript into something like:</p> <pre><code>$(document).ready(function(){ // init the selectables $('.selectable').each(function(){ $(this).find('li').not(':first').hide(); }); // assign the handlers for each control $('.selectable_control').each(function(){ var field_id = this.id.replace(/_selectable_control$/, ''), $selectable = $('#' + field_id + '_selectable'), $field = $('#' + field_id); $(this).find('.prev, .next').click(function(){ // Determine the direction var dir = $(this).hasClass('prev') ? 'prev' : 'next'; // Get the li that is currently visible var current = $selectable.find('li:visible'); // Get the element that should be shown next according to direction var next = dir == 'prev' ? current.prev('li') : current.next('li'); // If there's no more in that direction, select first/last if(next.length === 0) { next = dir == 'prev' ? $selectable.find('li:last') : $selectable.find('li:first'); } // Hide them all.. $selectable.find('li').hide(); // And show the new one next.show(); // And update the corresponding field $field.val( next.text() ); return false; }); }); }); </code></pre> <p>The end result is that you're grouping the control blocks, selectables, and fields, allowing for you to store the selected values as desired.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload