Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a drop-down multiple times

Is it possible to write a <select> menu and use it in multiple places on web page?

example:

<select id="dm">
  <option value="">Select Quantity</option>
  <option value="less ">50 - 60</option>
  <option value="medium ">61 - 70</option>
  <option value="large ">71 - 80</option>
  <option value="xl ">Above 80</option>
</select>

How can I use this menu multiple times within the same webpage?

like image 801
Nelie Avatar asked Mar 20 '26 23:03

Nelie


2 Answers

Give the <select> a class and then you can use the jQuery clone() function.

<select class="dropClass" id="dm">
  <option value="">Select Quantity</option>
  <option value="less ">50 - 60</option>
  <option value="medium ">61 - 70</option>
  <option value="large ">71 - 80</option>
  <option value="xl ">Above 80</option>
</select>

<div id="someDiv"><!-- you want the dropdown here too --></div>

$( ".dropClass" ).clone().appendTo( "#someDiv" );

DEMO

like image 149
LinkinTED Avatar answered Mar 22 '26 12:03

LinkinTED


Keep the original in a dummy script block as a template (text/template is not recognized so is ignored).

<script id="dm" type="text/template">
    <select>
       <option value="">Select Quantity</option>
       <option value="less ">50 - 60</option>
       <option value="medium ">61 - 70</option>
       <option value="large ">71 - 80</option>
       <option value="xl ">Above 80</option>
    </select>
</script>

Create copies using:

var copy = $('#dm').html();
something.append(copy);

This avoids the unique id issue (as the select has no id). It is also very easy to read/maintain.

As suggested below, if you want to use this in a form, the select must be named:

var $copy = $($('#dm').html()).attr('name', newMenuName);
something.append(copy);

note: The extra $() converts the string to a DOM element first before adding the attribute.

like image 45
Gone Coding Avatar answered Mar 22 '26 12:03

Gone Coding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!