Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- <form name="form">
- <button id="addCountry">Add county list</button>
- </form>
- <script>
- const addCountry = document.querySelector('#addCountry');
- const form = document.forms.form;
- let currentCountry = '';
- function getSelectedCountries() {
- return Array.from(form.countries).map(country => country.value);
- }
- function handleChangeCountry(event) {
- const element = event.target;
- if (element.nodeName === 'SELECT') {
- const countries = getSelectedCountries();
- if (countries.includes(currentCountry)) {
- alert('Country already selected');
- element.value = currentCountry;
- }
- }
- }
- function handleFocusCountry(event) {
- const element = event.target;
- if (element.nodeName === 'SELECT') {
- currentCountry = element.value;
- }
- }
- function handleClickButton(event) {
- event.preventDefault();
- const countryList = ['Nicaragua', 'Costa rica', 'Honduras', 'El salvador', 'Guatemala', 'Panama'];
- const select = document.createElement('select')
- const form = document.forms.form;
- select.name = 'countries';
- select.id = 'countries';
- countryList.forEach(country => {
- const option = new Option(country, country)
- select.appendChild(option);
- });
- form.appendChild(select);
- }
- addCountry.addEventListener('click', handleClickButton);
- form.addEventListener('change', handleChangeCountry);
- form.addEventListener('focus', handleFocusCountry);
- </script>
- </body>
- </html>
Add Comment
Please, Sign In to add comment