JSFiddle - React, Tailwind, and code Playground
by velo_ninja
HTML
<!-- HTML Section -->
<div id="container">
<button id="myButton">Click me to create dropdown</button>
</div>
JavaScript
// JavaScript Section
function handleClick(titleInput) {
console.log('Click');
var options = ['Option 1', 'Option 2', 'Option 3'];
// Make sure titleInput is a valid DOM element
if (titleInput && titleInput instanceof HTMLElement) {
createDropdown(titleInput, options);
} else {
console.error('titleInput is not a valid DOM element');
}
}
function createDropdown(titleInput, optionsArray) {
console.log('Creating dropdown...');
// Create the div element
var dropdownDiv = document.createElement('div');
dropdownDiv.id = 'dropdownDiv';
dropdownDiv.style.marginTop = '20px';
// Create the select element
var selectElement = document.createElement('select');
selectElement.id = 'dropdown';
// Loop through the array and create option elements
optionsArray.forEach(function(optionValue) {
var option = document.createElement('option');
option.value = optionValue.toLowerCase().replace(/\s+/g, ''); // Set the value attribute
option.textContent = optionValue; // Set the visible text
selectElement.appendChild(option); // Append option to select
});
// Append the select element to the div
dropdownDiv.appendChild(selectElement);
// Append the dropdownDiv to the titleInput container
titleInput.appendChild(dropdownDiv);
}
// Attach click event to the button
document.getElementById('myButton').addEventListener('click', function() {
var container = document.getElementById('container');
handleClick(container); // Pass the 'container' as the parent element
});