Reputation: 93
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?
Upvotes: 3
Views: 4834
Reputation: 93561
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.
Upvotes: 2
Reputation: 6131
Using a templating engine such as Handlebar or similar would be easy, but might be over kill in your case.
I would simply store the complete HTML code in a variable, and then inject that variable wherever I need it for future use. Problem here is complexity and maintainability of the HTML code. In any case something like this (using jQuery):
JS:
var myDropDown = 'youthtmlcode is here'
$("#myDropDown").html(myDropDown);
HTML:
<div id="myDropDown"></div>
Upvotes: 0
Reputation: 18123
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" );
Upvotes: 3