Guest User

Untitled

a guest
May 23rd, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <form name="form">
  10. <button id="addCountry">Add county list</button>
  11. </form>
  12.  
  13. <script>
  14. const addCountry = document.querySelector('#addCountry');
  15. const form = document.forms.form;
  16. let currentCountry = '';
  17.  
  18. function getSelectedCountries() {
  19. return Array.from(form.countries).map(country => country.value);
  20. }
  21.  
  22. function handleChangeCountry(event) {
  23. const element = event.target;
  24.  
  25. if (element.nodeName === 'SELECT') {
  26. const countries = getSelectedCountries();
  27.  
  28. if (countries.includes(currentCountry)) {
  29. alert('Country already selected');
  30.  
  31. element.value = currentCountry;
  32. }
  33. }
  34. }
  35.  
  36. function handleFocusCountry(event) {
  37. const element = event.target;
  38.  
  39. if (element.nodeName === 'SELECT') {
  40. currentCountry = element.value;
  41. }
  42. }
  43.  
  44. function handleClickButton(event) {
  45. event.preventDefault();
  46.  
  47. const countryList = ['Nicaragua', 'Costa rica', 'Honduras', 'El salvador', 'Guatemala', 'Panama'];
  48. const select = document.createElement('select')
  49. const form = document.forms.form;
  50.  
  51. select.name = 'countries';
  52. select.id = 'countries';
  53.  
  54. countryList.forEach(country => {
  55. const option = new Option(country, country)
  56.  
  57. select.appendChild(option);
  58. });
  59.  
  60. form.appendChild(select);
  61. }
  62.  
  63. addCountry.addEventListener('click', handleClickButton);
  64. form.addEventListener('change', handleChangeCountry);
  65. form.addEventListener('focus', handleFocusCountry);
  66. </script>
  67. </body>
  68. </html>
Add Comment
Please, Sign In to add comment