0

I have to show a dropdown list of 250 countries in a html page. I can do it easily do it by below

<select id="country" name="country">
<option value="1">Afghanistan</option>
<option value="2">Albania</option>
.....
<option value="250">Canary Islands</option>
</select>

I have to use 5 times the same list in a html page. so, how can i reduce repeat work?

2 Answers 2

2

You can use jQuery's clone to clone the element: http://api.jquery.com/clone/

for(var i=0; i<5; i++) {
  $("body").append($("#country").clone(false).prop("id", "country"+i));
}

This will clone the country dropdown 5 times, changing the ID property of each to make it unique, then append it to the page.

Sign up to request clarification or add additional context in comments.

Comments

0

Here's another option in plain ol' JavaScript:

var cloneList = function(){
 return this.cloneNode();
}.bind(document.getElementById('country'));

var count = 5;
while(count--) document.body.appendChild(cloneList()).id = 'country' + count;

You can reuse the cloneList function whenever you need it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.