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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With